保留列是一个varchar,对它执行求和我想将它转换为deciaml.但是下面的SQL给了我一个错误
select
cast(Reserve as decimal)
from MyReserves
Run Code Online (Sandbox Code Playgroud)
将数据类型varchar转换为数字时出错.
我添加了isnumeric而不是null来尝试避免这个错误,但它仍然存在,任何想法为什么?
select
cast(Reserve as decimal)
from MyReserves
where isnumeric(Reserve ) = 1
and MyReserves is not null
Run Code Online (Sandbox Code Playgroud)
请参见此处:CAST和IsNumeric
试试这个:
WHERE IsNumeric(Reserve + '.0e0') = 1 AND reserve IS NOT NULL
Run Code Online (Sandbox Code Playgroud)
UPDATE
十进制的默认值是(18,0),所以
declare @i nvarchar(100)='12121212121211212122121'--length is>18
SELECT ISNUMERIC(@i) --gives 1
SELECT CAST(@i as decimal)--throws an error
Run Code Online (Sandbox Code Playgroud)
天哪,似乎没有人正确解释过这一点。SQL 是一种描述性语言。它没有指定操作的顺序。
您(好吧,曾经)遇到的问题是where在转换发生之前没有进行过滤。但是,操作顺序对于 case 语句是有保证的。因此,以下将起作用:
select cast(case when isnumeric(Reserve) = 1 then Reserve end as decimal)
from MyReserves
where isnumeric(Reserve ) = 1 and MyReserves is not null
Run Code Online (Sandbox Code Playgroud)
该问题与您要转换为的特定数字格式或isnumeric()函数无关。只是无法保证操作的顺序。
小智 4
看来 isnumeric 有一些问题:
http://www.sqlhacks.com/Retrieve/Isnumeric-problems (通过互联网档案)
根据该链接,您可以这样解决:
select
cast(Reserve as decimal)
from MyReserves
where MyReserves is not null
and MyReserves * 1 = MyReserves
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20093 次 |
| 最近记录: |