views:

175

answers:

2

I have a SQL Server 2000 database with a column of type VARCHAR(255). All the data is either NULL, or numeric data with up to two points of precision (e.g. '11.85'). I tried to run the following T-SQL query but received the error 'Error converting data type varchar to numeric'

SELECT CAST([MyColumn] AS DECIMAL)
FROM [MyTable];

I tried a more specific cast, which also failed.

SELECT CAST([MyColumn] AS DECIMAL(6,2))
FROM [MyTable];

I also tried the following to see if any data is non-numeric, and the only values returned were NULL.

SELECT ISNUMERIC([MyColumn]), [MyColumn]
FROM [MyTable]
WHERE ISNUMERIC([MyColumn]) = 0;

I tried to convert to other data types, such as FLOAT and MONEY, but only MONEY was successful. So I tried the following:

SELECT CAST(CAST([MyColumn] AS MONEY) AS DECIMAL)
FROM [MyTable];

...which worked just fine. Any ideas why the original query failed? Will there be a problem if I first convert to MONEY and then to DECIMAL?

Thanks!

+3  A: 

It's likely that this depends on whether the decimal symbol is a comma or a dot. Here are some test queries and their results:

select CAST('3.6' as decimal) -- 3.60
select CAST('3,6' as decimal) -- Error converting data type varchar to numeric.
select CAST('3.6' as money) -- 3.60
select CAST('3,6' as money) -- 36.00 (!)
select ISNUMERIC('3.6') -- 1
select ISNUMERIC('3,6') -- 1

The documentation for ISNUMERIC says :

ISNUMERIC returns 1 when the input expression evaluates to a valid integer, floating point number, money or decimal type; otherwise it returns 0

Both 3.6 and 3,6 can be cast to money, so that's why isnumeric('3,6') returns 1.

To resolve this issue, replace the comma's with dots (or vice versa, if your system uses comma as the decimal symbol):

select cast(replace('3,6',',','.') as decimal)

Another option is to change the "decimal symbol" in Windows. It's in Config Panel -> Regional and Language -> Formats -> Additional Settings -> Numbers.

Andomar
It was a few records with commas instead of decimal points causing the problem. Thanks for the great answer!
Kevin Babcock
A: 

Select CAST(isnull(MyColumn,0) as Decimal(4,2)) FROM [MyTable];

Sasikiran