views:

253

answers:

2

I'm looking for an elegant way to convert a field of type varchar, with variable data in it, to a data type which can be used for mathematical operations sample data from the field (excluding quotes)

''
'abc'
'23'
'23.2'

The method should work for all, and for the first & second values should return 0, and not throw an SQL Server error..

A: 
SELECT  CASE IsNumeric(mycol) WHEN 1 THEN CAST(mycol AS FLOAT) ELSE 0 END
FROM    mytable
Quassnoi
+2  A: 

Try this:

SELECT CASE WHEN IsNumeric(YourColumn) = 0 THEN 
           0 
       ELSE 
           CAST(YourColumn AS decimal(18, 2)) 
       END

You have to adjust the destination data type, I have chosen decimal(18, 2) for demonstration.

Maximilian Mayerl
+1 you beat me by seconds :-)
marc_s
IsNumeric is a nasty little function, as long as a type converts to any of the numeric types it returns 1, but you do not know which type is has agreed it can convert to, so for the input '£1.20' it will throw an error on the cast, even though it passed the isnumeric.
Andrew
thanks for this information
pablo
what would you do then to avoid $1.20 error?
pablo
It is incredibly difficult to £1.2 will convert to money, which is why the IsNumeric allows it, but refuses to convert to anything else. '1e1' is numeric because it can will convert to a real or float, but not to an int, even thought the result is a whole number. I've never seen a compelling solution, it's already been covered in http://stackoverflow.com/questions/312054/efficient-isnumeric-replacements-on-sql-server for examples of workarounds, all with pros and cons.
Andrew