Skip to content

TRY_CAST

TRY_CAST( expression AS data_type [ ( length ) ] )

Section titled “TRY_CAST( expression AS data_type [ ( length ) ] )”
  • expression: The value to be converted. The expression must be a valid expression of any one of the data types in the character string and binary data type category, except for the xml data type.
  • data_type: The target data type to convert the expression into. It can be any valid data type into which SQL Server can implicitly convert the expression data type.
  • length: An optional parameter to specify the length of the target data type. This is only applicable for some data types like varchar where specifying the length is mandatory.
SELECT TRY_CAST('2012-06-30' AS DATE) AS Result;
Result
----------
2012-06-30

In the above example, the TRY_CAST function tries to cast the string '2012-06-30' as a DATE datatype. Since the conversion is successful, it returns the date 2012-06-30.