Microsoft SQL Server TRY CAST


Example

SQL Server 2012

It converts value to specified data type and if conversion fails it returns NULL. For example, source value in string format and we need it in double/integer format. Then this will help us in achieving it.

Syntax: TRY_CAST ( expression AS data_type [ ( length ) ] )

TRY_CAST() returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Expression - The source value which will go to cast.
Data_type - The target data type the source value will cast.
Length - It is an optional parameter that specifies the length of target data type.

DECLARE @sampletext AS VARCHAR(10);  
SET @sampletext = '123456';  
  
SELECT TRY_CAST(@sampletext AS INT); -- 123456  
SELECT TRY_CAST(@sampletext AS DATE); -- NULL