TRY_CAST

TRY_CAST is a SQL function that attempts to convert an expression of one data type to another. If the conversion is successful, it returns the value in the specified data type. If the conversion fails, instead of throwing an error, it returns NULL.

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.

Example

SELECT TRY_CAST('2012-06-30' AS DATE) AS Result;

Output

Result
----------
2012-06-30

Explanation

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.

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