SQL Server TRY_CAST() Function: Cast to DataType

SQL Server TRY_CAST() function returns a value cast to the specified type if successful, else returns NULL.

The main difference between TRY_CAST() and the CAST() function is the way unsuccessful castings are handled. For unsuccessful cast operation, the TRY_CAST() returns a NULL whereas the CAST() function returns an error.

TRY_CAST(expression AS data_type[(length)])


expression: Any valid expression whose value is to be cast.

data_type: The data type into which the expression will be cast.

length: An optional parameter that specifies the length of the target data type.

Return Value

Returns the expression cast into the target data type if CAST() succeeds else returns NULL.

Example 1:

In the following example, a decimal value is converted to as int.

Example: TRY_CAST()
SELECT TRY_CAST(1234.56 AS int) AS Result;

Example 2:

In this example, a string in the expected date format is converted to a datetime type.

Example: TRY_CAST()
SELECT TRY_CAST('12/02/2022' AS datetime) AS Result;

Example 3:

This example demonstrates the TRY_CAST() function returning a NULL value when it doesn’t succeed.

Example: TRY_CAST()
SELECT TRY_CAST('Hello' AS int) AS Result;
Want to check how much you know SQL Server?