TRY_CONVERT
TRY_CONVERT( data_type [ ( length ) ], expression [, style ] )
Section titled “TRY_CONVERT( data_type [ ( length ) ], expression [, style ] )”- data_type [( length )]: The target data type to which the expression should be converted. This includes an optional length that specifies the length of the target type. For example, VARCHAR(30).
- expression: The value to be converted. It can be a column or a string that is convertible to the target type.
- style: Optional parameter. When used, it indicates how the TRY_CONVERT function should translate the expression into the data type. Matters for date and time conversion.
Example
Section titled “Example”SELECT TRY_CONVERT(float, '123.45') AS 'Float Conversion', TRY_CONVERT(int, 'ABC') AS 'Integer Conversion'Output
Section titled “Output”Float Conversion Integer Conversion123.45 NULLExplanation
Section titled “Explanation”The TRY_CONVERT function attempts to convert a value from one data type to another. If successful, the converted value is returned; otherwise, NULL is returned. In the provided example, the string ‘123.45’ was successfully converted to a float, whereas the string ‘ABC’ could not be converted to an integer, so NULL was returned.