嗨,我有一个值,我想确保它在存储过程中只是数字。我有以下代码
if (IsNumeric(myField) =0)
begin
--does some work
end;
如果数字不是数字,它应该检查 myField,如果不是,它会继续工作。由于某种原因,上面的代码抛出错误。知道如何解决这个问题。错误是异常被抛出 varchar 到 int。请让我知道,谢谢
嗨,我有一个值,我想确保它在存储过程中只是数字。我有以下代码
if (IsNumeric(myField) =0)
begin
--does some work
end;
如果数字不是数字,它应该检查 myField,如果不是,它会继续工作。由于某种原因,上面的代码抛出错误。知道如何解决这个问题。错误是异常被抛出 varchar 到 int。请让我知道,谢谢
As others have pointed out, isnumeric()
will return 1 on occasions where the string cannot be converted.
The following tests for a positive integer:
where myfield not like '%[^0-9]%'
The following tests for a positive integer or floating point number:
where myfield not like '%[^0-9.]%' and myfield not like '%.%.%'
As a note, none of these methods test for numeric overflow. You could test for that with something like:
where myfield not like '%[^0-9]%' and len(myfield) <= 10 and myfield <= '2147483647'
(assuming there are no leading 0s).
您的表达式是有效的,我怀疑您得到的值被函数视为数字,但无法转换为整数。尝试以下...
declare @myfield varchar(20)
set @myfield='.'
if ISNUMERIC(@myfield)=1
begin
select CONVERT(int,@myField)
end
convert 语句将因您报告的错误而爆炸...
检查这个问题: T-sql - 确定值是否为整数
无法转换为整数的“数字”值的更多示例
select '1.e0',ISNUMERIC('1.e0') as IsNum
union
select '.',ISNUMERIC('.') as IsNum
union
select '12.31',ISNUMERIC('12.31') as IsNum
在中添加选择convert(int,myField)
以begin/end
查看导致错误发生的实际字段值
像这样检查它:
if (IsNumeric(myField))
begin
--does some work
end;