Problem convert column values from VARCHAR(n) to DECIMAL

徘徊边缘 提交于 2019-12-10 20:19:11

问题


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!


回答1:


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.




回答2:


Another cause is empty strings. For example, if you use the import wizard to import a CSV file, empty fields will become empty strings, not nulls.

This is a common idiom for fixing this:

CAST(NULLIF([number_as_a_string],'') AS decimal(13,2))



回答3:


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



来源:https://stackoverflow.com/questions/2589103/problem-convert-column-values-from-varcharn-to-decimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!