首页 > 解决方案 > 检查 varchar 列是否为数字

问题描述

所以我有一个varchar数据类型的列,用户可以输入 100000、-1000000 等值。我需要验证该列是否有数字

-10000 有效

100.32 有效

100,000 无效

所以我下来使用

select * from mytable where isnumeric(replace([mycol],',','*')) <>1

或者

select * from mytable where TRY_CAST([mycol] as FLOAT) IS NULL

我可以通过这两种方法完成我的工作,但我想知道哪种方法有效。还是有更好的方法来完成工作

标签: sql-server

解决方案


您可以检查数据是否可以转换为指定的转换try_cast(),如下所示。

null如果不能转换为您正在尝试的指定转换,它将返回。

create table MyTable (Data varchar(20))
insert into MyTable values
('-10000'), ('100.32'), ('100,000')

Select Data
 Data
 , try_Cast(Data as decimal) DataInDecimal
 , try_cast(Data as int) DataInInteger
from MyTable

现场db<>fiddle演示。


推荐阅读