Latest Post

Monday, 24 October 2016

How to Use TRY_CAST() SQL function

TRY_CAST() function

TRY_CAST() function is introduced in SQL Server 2012. it is used  to cast input string to the specified data type. it returns null  if casting fails otherewies it returns a value cast to the specified data type.

Syntax:- TRY_CAST ( input_value AS data_type)


Example:-

 DECLARE @InputString AS VARCHAR(50);  
SET @InputString = 'www.code-view.com';  
  
SELECT TRY_CAST(@InputString AS varchar(50)); -- www.code-view.com  
SELECT TRY_CAST(@InputString AS DATE); -- NULL 




Firstly, query converts successfully and will gives "www.code-view.com" result, but in second query the conversion fails and it returns NULL