Tuesday, August 9, 2011

SQL Server Denali : TRY_CONVERT(), a Good Addition

While working with different type of 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 correct rows. SQL Server never mentions which row is the culprit, it just throw an error. Sometime you want to ignore those problematic rows but can’t because you have no other option to found those wrong data.You can correct them manually or write an intelligent 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 select query 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 what will I do, so I can execute my query without any error.
SELECT CASE ISNUMERIC(Val1)
       WHEN 1 THEN 
              CASE LEFT(Val1,1)
              WHEN '$' THEN NULL
              ELSE CONVERT(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(). This function try to convert values according to your given format and if failed it will return NULL (instead of error). Let’s try this amazing function.
SELECT TRY_CONVERT(float,Val1)  AS Val1
FROM #TempTable
 























------------------------------------------------------------------------------------
Read More about SQL Server 2012 (Code Name: Denali

·         Introducing New Edition "Business Intelligence"

·         Changing Backup Files Default Path is More Easy Now

·         New Backup/Restore Options

·         CTP 3 Product Guide Released

·         Table Partition Limit Enhancement

·         Format(), a Most Wanted Function

·         Get Date/Time from Parts

·         New Function to Get Last Date of Month

·         IIF Logical Function

·         A New More Flexible Create Index Dialog box

No comments:

Post a Comment

All suggestions are welcome