SQL Server Denali : TRY_CONVERT(), a Good Addition
While working with different typeof data, I have not found a single day, without data type conversion error.Sometime error could be just because of a single row, out of million of correctrows. SQL Server never mentions which row is the culprit, it just throw anerror. Sometime you want to ignore those problematic rows but can’t because youhave no other option to found those wrong data.You can correct them manually or write anintelligent query. Consider following simple example
CREATE TABLE #TempTable (Val1 VARCHAR(10))
INSERT INTO #TempTable
SELECT ‘2.01’ UNION ALL
SELECT ‘A2.4’ UNION ALL
SELECT ‘6.51’ UNION ALL
SELECT ‘$37’ UNION ALL
SELECT CONVERT(float,Val1) AS Val1
Result of above selectquery is an error, because row:2 data can’t be converted into float.
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.
So whatwill I do, so I can execute my query without any error.
SELECT CASE ISNUMERIC(Val1)
WHEN 1 THEN
WHEN‘$’ THEN NULL
ELSE NULL END AS Val1
To avoid such error, with out writing long quires, SQL Server Denali has introduced a new function TRY_CONVERT(). Thisfunction try to convert values according to your given format and if failed itwill return NULL (instead of error). Let’s try this amazing function.
SELECT TRY_CONVERT(float,Val1) AS Val1