T-SQL Tutorial T-SQL Advanced Database Management T-SQL References

T-SQL TRY_CAST() Function



The T-SQL (Transact-SQL) TRY_CAST() function tries to convert an expression from one datatype to another datatype. If the conversion fails, the function will return NULL. Otherwise, it will return the converted value.

Note: CAST() function is similar to this function except the CAST() function returns an error (instead of NULL) if the conversion fails.

Syntax

TRY_CAST(expression AS data_type [ ( length ) ])

Parameters

expression Required. Specify the value to convert to another datatype.
data_type Required. Specify the datatype to convert to. See the data types of T-SQL. Note that the Alias data types cannot be used.
length Optional. Specify the length of the resulting data type, for data types that allow a user specified length. Default is 30.

Return Value

Returns the expression converted to another data_type.

Convert to INT

The TRY_CAST() function can be used to convert a value to a INT type. For example - in the example below, 123.456 is converted to INT datatype.

SELECT TRY_CAST(123.456 AS INT);
Result: 123

Convert to DECIMAL

The TRY_CAST() function can be used to convert a value to a DECIMAL type. For example - in the example below, '123.456' is converted to DECIMAL datatype.

SELECT TRY_CAST('123.456' AS DECIMAL(5, 2));
Result: 123.46

Convert to CHAR

The TRY_CAST() function can be used to convert a value to a CHAR type. For example - in the example below, 123 is converted to CHAR datatype.

SELECT TRY_CAST(123 AS CHAR(4));
Result: '123'

Convert to NCHAR

The TRY_CAST() function can be used to convert a value to a NCHAR type. For example - in the example below, 123 is converted to NCHAR datatype.

SELECT TRY_CAST(123 AS NCHAR(10));
Result: '123'

Convert to VARCHAR

The TRY_CAST() function can be used to convert a value to a VARCHAR type. For example - in the example below, 123 is converted to VARCHAR datatype.

SELECT TRY_CAST(123 AS VARCHAR);
Result: '123'

Convert to DATE

The TRY_CAST() function can be used to convert a value to a DATE type. For example - in the example below, '2018-08-18' is converted to DATE datatype.

SELECT TRY_CAST('2018-08-18' AS DATE);
Result: '2018-08-31'

Convert to TIME

The TRY_CAST() function can be used to convert a value to a TIME type. For example - in the example below, '10:38:42' is converted to TIME datatype.

SELECT TRY_CAST('10:38:42' AS TIME);
Result: '10:38:42'

Convert to DATETIME

The TRY_CAST() function can be used to convert a value to a DATETIME type. For example - in the example below, '2018-08-18 10:38:42' is converted to DATETIME datatype.

SELECT TRY_CAST('2018-08-18 10:38:42' AS DATETIME);
Result: '2018-08-18 10:38:42'

❮ T-SQL Functions