sql-server - 检查 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
我可以通过这两种方法完成我的工作,但我想知道哪种方法有效。还是有更好的方法来完成工作
解决方案
您可以检查数据是否可以转换为指定的转换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演示。
推荐阅读
- api - OneSignal api 有时会响应“假”有时会发送正确的响应
- javascript - jQuery 可选列表作为日历
- javascript - 你如何在打字稿中声明一个对象数组?
- javascript - 在 chrome IOS 选项卡上打开 base64 pdf
- qt - 如何使用 MapCircle 与 Mapobject [在函数中]?
- arrays - 索引numpy两个数组
- c++ - 返回对成员变量数据的引用的开销
- image-processing - 使图像仅以灰度显示
- android - 在 Kotlin 中将值从 Activity 传递到 Fragment
- python - 使用 Kivy 连接的 GridLayout 对象没有属性标题