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 ’56’
GO
—Simple convert
SELECT CONVERT(float,Val1)  AS Val1
FROM #TempTable
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 
              CASELEFT(Val1,1)
              WHEN‘$’ THEN NULL
              ELSECONVERT(float,Val1) END 
       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
FROM #TempTable
 

Advertisements

Posted on August 9, 2011, in Daily Dose. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: