TRY_CAST#

Converts a value to a specified data type, like CAST, but returns NULL instead of an error when the value cannot be converted.

Syntax#

TRY_CAST ( expression AS data_type [ ( length ) ] )

Return type#

data_type, always nullable. A varchar or nvarchar without a length is 30 characters long.

Examples#

SELECT TRY_CAST('12' AS int);              -- 12
SELECT TRY_CAST('abc' AS int);             -- NULL
SELECT TRY_CAST(300 AS tinyint);           -- NULL
SELECT TRY_CAST('abcdef' AS varchar(3));   -- abc
SELECT TRY_CAST('2024-02-30' AS date);     -- NULL

SELECT s, TRY_CAST(s AS int) AS n
FROM (SELECT '1' AS s UNION ALL SELECT 'x' UNION ALL SELECT '3') AS v; -- 1, NULL, 3

Remarks#

Only the conversion of the value itself returns NULL, whatever the ANSI_WARNINGS, ARITHABORT and NUMERIC_ROUNDABORT settings are. Everything else still raises, as in SQL Server:

  • An error raised while computing the value, for example TRY_CAST(1/0 AS int) or TRY_CAST(CAST('a' AS int) AS varchar(10)).

  • A conversion between two data types that is not allowed at all, such as TRY_CAST(1 AS xml) or a varchar(max) value converted to sql_variant. This raises error 529 when the statement is compiled, even when no row is converted.

  • A sql_variant value whose contained type cannot be converted to the target type, for example a date converted to int.

A conversion that succeeds by truncating keeps the result of CAST: TRY_CAST(123456 AS varchar(3)) returns *.

TRY_CAST is not a reserved keyword: it can still be used as a column name or an alias.

Note

On a SQL Server data source Querona sends TRY_CAST to the source, except a conversion between character text and a date or time, or of a sql_variant to text or a date or time, whose answer depends on the session’s DATEFORMAT and LANGUAGE. On other data sources, and for such a conversion, Querona reads the value from the source and converts it itself, so a WHERE condition on TRY_CAST filters the rows in Querona, not in the source.

Written with a comma instead of AS, as in TRY_CAST('1', 'int'), the call is reported as an unknown function rather than with SQL Server’s error 1035. See Feature support.

See Also#