TRY_CONVERT (Transact-SQL)
Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
TRY_CONVERT takes the value passed to it and tries to convert it to the specified data_type. If the cast succeeds, TRY_CONVERT returns the value as the specified data_type; if an error occurs, null is returned. However if you request a conversion that is explicitly not permitted, then TRY_CONVERT fails with an error.
TRY_CONVERT is a new keyword in compatibility level 110.
This function is capable of being remoted to servers that have a version of SQL Server 2012 and above. It will not be remoted to servers that have a version below SQL Server 2012.
A. TRY_CONVERT returns null
The following example demonstrates that TRY_CONVERT returns null when the cast fails.
SELECT CASE WHEN TRY_CONVERT(float, 'test') IS NULL THEN 'Cast failed' ELSE 'Cast succeeded' END AS Result; GO
Here is the result set.
Result ------------ Cast failed (1 row(s) affected)
The following example demonstrates that the expression must be in the expected format.
SET DATEFORMAT dmy; SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result; GO
Here is the result set.
Result ---------------------- NULL (1 row(s) affected)
B. TRY_CONVERT fails with an error
The following example demonstrates that TRY_CONVERT returns an error when the cast is explicitly not permitted.
SELECT TRY_CONVERT(xml, 4) AS Result; GO
The result of this statement is an error, because an integer cannot be cast into an xml data type.
Explicit conversion from data type int to xml is not allowed.
C. TRY_CONVERT succeeds
This example demonstrates that the expression must be in the expected format.
SET DATEFORMAT mdy; SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result; GO
Here is the result set.
Result ---------------------------------- 2010-12-31 00:00:00.0000000 (1 row(s) affected)