0

I have a table called testTable with two columns, id that is auto incremented and someValue.

The data contained in the someValue column are: 12, 1.2, .4, 1d4, +, -, .

Data type for someValue is varchar(50).

Why are the following queries throwing

Error converting data type varchar to numeric.

select ID, someValue 
from testTable 
where ISNUMERIC(someValue + 'd0') = 1 and CAST(someValue as decimal(8,2)) > 0.1;

select tt.ID,tt.someValue 
from (select ID, someValue 
      from testTable 
      where ISNUMERIC(someValue + 'd0') = 1) as tt 
where CAST(tt.someValue as decimal(8,2)) > 0.1;
4

2 回答 2

1

你有几个问题;CAST不适用于非十进制输入,并ISNUMERIC接受可以转换为货币金额的字符串,包括非十进制值,例如“-”、“.”或“US$100”。

解决此问题的正确方法是在Decimal数据库中添加一列,使用要比较的值someValue填充列,然后仅与列进行比较。DecimalDecimal

如果由于某种原因你不能这样做,你可以使用ISNUMERIC并且只包括非货币小数金额,并使用Convert而不是CAST

select ID, someValue 
from testTable 
where ID IN
    (select ID from testTable where ISNUMERIC(someValue) = 1
    AND Patindex('%[^0-9-+.]%', someValue) = 0
    AND someValue NOT IN ('-', '+', '.')
    )
    and Convert(decimal, someValue) > 0.1
于 2013-01-29T01:15:10.457 回答
0

在您的第一个陈述中,您直接从testTable并尝试:

CAST(someValue as  decimal(8,2))

这将引发错误,因为您没有过滤掉非数值。

于 2013-01-28T16:59:59.907 回答