gra*_*ady 58 t-sql numerical-methods
有没有一种简单的方法来确定varchar是否是一个数字?
例子:
abc123 - >没有号码
123 - >是的,它是一个数字
谢谢 :)
Dam*_*ver 131
ISNUMERIC不会这样做 - 它告诉你字符串可以转换为任何数字类型,这几乎总是一个无知的信息.例如,根据ISNUMERIC,以下所有内容均为数字:
£,$,0d0
如果要检查数字和只检查数字,可以使用负LIKE表达式:
not Value like '%[^0-9]%'
Run Code Online (Sandbox Code Playgroud)
Bin*_*nil 26
你可以这样检查
declare @vchar varchar(50)
set @vchar ='34343';
select case when @vchar not like '%[^0-9]%' then 'Number' else 'Not a Number' end
Run Code Online (Sandbox Code Playgroud)
Dan*_*eld 19
使用SQL Server 2012+,如果您有特定需求,可以使用TRY_*函数.例如,
-- will fail for decimal values, but allow negative values
TRY_CAST(@value AS INT) IS NOT NULL
-- will fail for non-positive integers; can be used with other examples below as well, or reversed if only negative desired
TRY_CAST(@value AS INT) > 0
-- will fail if a $ is used, but allow decimals to the specified precision
TRY_CAST(@value AS DECIMAL(10,2)) IS NOT NULL
-- will allow valid currency
TRY_CAST(@value AS MONEY) IS NOT NULL
-- will allow scientific notation to be used like 1.7E+3
TRY_CAST(@value AS FLOAT) IS NOT NULL
Run Code Online (Sandbox Code Playgroud)