isNumeric() - it can not be right?


hi,

i am migrating data from a legacy system with a not nice front-end.
as a result, i have all sorts of garbage stored on the tables.

i am trying to convert values from varchar(12) to float, but i have an error during selecting data that says that data can not be converted eventhough i am using the ISNUMERIC() function to check.

case when
isNumeric( myCol01 ) = 0 then null
else
convert( float , myCol01 )
end

but my error occours when ISNUMERIC() encounters the value '. ' ; that is a dot with spaces after it.

try the expression below;

SELECT

myValue = '. '
, is_numeric = ISNUMERIC('. ')
, converted = CONVERT( FLOAT , '. ')

has anyone got any idea how to work around this?

nicolas

[1164 byte] By [nicolasdiogo] at [2007-12-19]
# 1

If you use the ISNUMERIC function to determine if a value is numeric you might be in for a surprise
Run the 3 lines of code below and you will see what I mean

DECLARE @S VARCHAR(50)
SET @S = CHAR(9) @S NOW CONTAINS THE TAB CHARACTER
SELECT ISNUMERIC(@S), ISNUMERIC(CHAR(9)),ISNUMERIC('1D2'),ISNUMERIC('D')

As you can see TAB is returned as numeric as well the value 1D2
A better way to test for this would be with LIKE and %[a-z]%
If you run the example below you will see that the select statement with the ISNUMERIC function or LIKE returns one row more than the statement with LIKE and ISNUMERIC combined

CREATE TABLE #foo (Value VARCHAR(20))
INSERT INTO #foo
SELECT '1' UNION ALL
SELECT '3' UNION ALL
SELECT 'B' UNION ALL
SELECT '2' UNION ALL
SELECT '33.331' UNION ALL
SELECT 'adad1' UNION ALL
SELECT '1d2' UNION ALL
SELECT '^' UNION ALL
SELECT '17777.999'

--returns ^
SELECT * FROM #foo
WHERE Value NOT LIKE '%[a-z]%'

--returns 1d2
SELECT * FROM #foo
WHERE ISNUMERIC(Value) = 1

--returns correct result
SELECT * FROM #foo
WHERE Value NOT LIKE '%[a-z]%'
AND ISNUMERIC(Value) = 1

Denis the SQL Menace

http://sqlservercode.blogspot.com/

SQL_Menace at 2007-9-8 > top of Msdn Tech,SQL Server,Transact-SQL...
# 2

Hi,

ISNUMERIC() is comparing to a money datatype, so the "," and "$" is all numeric.
There is a good article about that:

http://www.aspfaq.com/show.asp?id=2390

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

JensSuessmeyer at 2007-9-8 > top of Msdn Tech,SQL Server,Transact-SQL...
# 3
i suppose it makes more sense to use a function to encasulate the logic for this check.
however, it seems absurd to have a function in mssql 200 that does not do what it was supposed to do.

what a shame..

thanks for your help Jens!

regards,

nicolas

nicolasdiogo at 2007-9-8 > top of Msdn Tech,SQL Server,Transact-SQL...

SQL Server

Site Classified