SQL Server 2012 introduces some useful conversion functions that will help you avoid errors when dealing with different data types. We will use easy-to-understand examples so you can see how beneficial they are.
TRY_PARSE
doesn't look too useful on surface, but as we will soon see it has a vey useful specialist niche.
The basic syntax of TRY_PARSE
is as follows:
SELECT TRY_PARSE (string AS datatype)
Each of the following will return a NULL
, as the value passed in the string does not convert to a value of the data type specified as the second parameter:
SELECT TRY_PARSE ('SQL Server 2012' AS datetime) AS MyDateTime SELECT TRY_PARSE ('SQL Server 2012' AS decimal) AS MyDecimal SELECT TRY_PARSE ('ABC' AS float) AS MyFloat
However, all of the following will return a date or numeric value equvalent to the string value:
SELECT TRY_PARSE ('03-07-2012' AS datetime) AS MyDateTime SELECT TRY_PARSE ('2012' AS decimal) AS MyDecimal1 SELECT TRY_PARSE ('2012.0' AS decimal)...