TRY_CONVERT

TRY_CONVERT is a SQL Server function that attempts to convert an expression of one data type into another. If the conversion fails, it returns NULL instead of raising an error.

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

SELECT TRY_CONVERT(float, '123.45') AS 'Float Conversion',
TRY_CONVERT(int, 'ABC') AS 'Integer Conversion'

Output

Float Conversion Integer Conversion
123.45 NULL

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.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.