The new TRY_CONVERT function is very similar to the CONVERT function except that it returns NULL when the conversion cannot be completed, such as attempting to put alphabetic characters into a numeric data type. If the conversion cannot be completed because the data type of the expression is not allowed to be explicitly converted to the specified data type, an error will be thrown.
The format for the TRY_CONVERT is this:
TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )
Notice that you have the option of specifying a style as you could with the CONVERT function.
An example of its use could be to try a conversion from a string input into a datetime data type where a NULL return means the user did not provide the proper input.
DECLARE @stringparm VARCHAR(30),
SET @stringparm = '2/30/2012'
SELECT @result = CASE WHEN TRY_CONVERT (datetime, @stringparm)
IS NULL THEN 'Bad Date'
ELSE 'Good Date'
-- -- -- -- -- -- -- -- -- --
Asked In: Many Interviews |