In SQL Server Denali, there are three new conversion functions being introduced, namely:
Today we will quickly take a look at the TRY_CONVERT() function. The TRY_CONVERT() function is very similar to CONVERT function which is avail in SQL Server already. Only difference is that it will attempt to CONVERT the datatype in specified datatype and while doing the same, if it fails (or error occurs) instead of displaying error it will return value NULL. Function CONVERT() is same as in earlier version (as far as I know till CTP3).
Now let us examine these examples showing how TRY_CONVERT() works:
Example1: Converting String to INT
-- No error
SELECT CONVERT(INT, '100') AS ValueInt;
SELECT TRY_CONVERT(INT, '100') AS ValueInt;
SELECT CONVERT(INT, 'A100.000') AS ValueInt;
SELECT TRY_CONVERT(INT, 'A100.000') AS ValueInt;
When you try first set where string can be converted to INT, it does not throw an error and it works fine.
However, in the second case wherein the string has an Alphabetic character, it cannot be converted to INT. In this case, CONVERT will throw an error but TRY_CONVERT will return a NULL result. Therefore, the major difference between CONVERT and TRY_CONVERT is that TRY_CONVERT will TRY to CONVERT and if CONVERT fails it will produce a NULL result instead of an error.
This distinct attribute separating the two functions are very helpful when we are using TRY_PARSE function over table. This is displayed in the examples below:
Example2: Using TRY_CONVERT with CASE statement.
CASE WHEN TRY_CONVERT(INT, '100') IS NULL
THEN 'Error In Result'
ELSE 'No Error'
END AS ValueInt;
The example above demonstrates how CASE statement can be used with TRY_PARSE, while avoiding any errors in the statement execution.
In the following example, TRY_PARSE is applied over table and it makes it more meaningful:
Example3: Converting String to INT from Table using TRY_CONVERT
You can clearly see that the PostalCode column in the database is in the format of the nvarchar. We can use CONVERT to convert it to INT.
SELECT SP.[StateProvinceCode], A.[PostalCode],
TRY_CONVERT(INT, A.[PostalCode]) PC_TryConvert
FROM [Person].[Address] A
INNER JOIN [Person].[StateProvince] SP
ON SP.StateProvinceID = A.StateProvinceID
When attempting to CONVERT a column, you might get one or more incorrect values. If the CONVERT function is used it will throw an error and will not return any results but with TRY_CONVERT it will not throw error but it will return the NULL value. As seen in example, the NULL value can be used along with CASE and desired message can be displayed.
In next blog post, we will discuss difference between CONVERT and PARSE as well TRY_CONVERT and TRY_PARSE. As well look at couple of interesting trivia questions.
Reference: Pinal Dave (https://blog.sqlauthority.com)