SELECT IsNumeric('472369326D4')
返回1。显然,字符串中有一个aphabet D
。为什么?
发布于 2018-08-22 11:22:52
472369326D4
是一个有效的float
类型。D
被转换为添加四个0
值,有效地将D
字符之前的值乘以10000
。
示例Sql
SELECT cast('472369326D4' as float)
SELECT cast('472369326D3' as float)
SELECT cast('472369326D2' as float)
输出:
4723693260000
472369326000
47236932600
发布于 2018-08-22 11:28:49
你可能想要这样的逻辑:
(case when str not like '%[^0-9]%' then 1 else 0 end) as isNumeric
或者,如果您想要允许小数和负号,那么逻辑就更麻烦了:
(case when str not like '%.%.%' and str not like '%[^.0-9]%' and
str not like '-%[^.0-9]%'
then 1 else 0
end)
我强烈建议不要使用isnumeric()
。它会产生奇怪的结果。除了“d”,“e”也是允许的。
在Server 2012+中,您可以尝试以下操作:
select x, isnumeric(x), try_convert(float, x)
from (values ('$'), ('$.'), ('-'), ('.')) v(x)
所有这些都返回1
表示isnumeric
,而返回NULL
表示转换,这意味着不能将值转换为浮点数。(您可以使用convert()
运行Server 2008中的代码,然后看着代码失败。)
https://stackoverflow.com/questions/51973704
复制