views:

1000

answers:

3

PRINT CONVERT(NUMERIC(18,0), '')

produces Error converting data type varchar to numeric.

However,

PRINT CONVERT(INT, '')

produces 0 without error...

Question: Is there some SQL Server flag for this or will I need to do case statements for every varchar to numeric conversion? (aside from the obvious why?)

A: 

Use ISNUMERIC

declare @a varchar(20)
set @a = 'notanumber'
select case when isnumeric(@a) = 0 then 0 else convert(numeric(18,0),@a) end
SqlACID
I guess I could refactor and put all these concerns in in-line functions. The only bad thing about case statements in a select statement is making the select statement three pages long.
Dr. Zim
The above won't work for all input strings, for example try @a='-' or @a='$'. See the article referenced in my answer.
Joe
+1  A: 

Empty string will convert to zero for float and int types, but not decimal. (And converts to 01 Jan 1900 for datetimes = zero). I don't know why.. it just is...

If you need decimal(18,0), use bigint instead. Or cast via float first

ISNUMERIC will accept "-" and "." and "1.2E3" as a number but this will all fail to convert to decimal.

gbn
+2  A: 

ISNUMERIC doesn't alway work as you might expect: in particular it returns True for some values that can't subsequently be converted to numeric.

This article describes the issue and suggests how to work around it with UDFs.

Joe