I am working in SQL Server 2008. I am trying to test whether a string (varchar) has only digit characters (0-9). I know that the IS_NUMERIC function can give spurious results.
I was attempting to find strings with numbers ONLY, no punctuation or anything else. I finally found an answer that would work here.
Using PATINDEX('%[^0-9]%', some_column) = 0 allowed me to filter out everything but actual number strings.
Method that will work. The way it is used above will not work.
declare @str varchar(50)='79136'
select
case
when @str LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
declare @str2 varchar(50)='79D136'
select
case
when @str2 LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
Use Not Like
where some_column NOT LIKE '%[^0-9]%'
declare @str varchar(50)='50'--'asdarew345'
select 1 where @str NOT LIKE '%[^0-9]%'
Solution:
where some_column NOT LIKE '%[^0-9]%'
Is correct.
Just one important note: Add validation for when the string column = ''
(empty string). This scenario will return that ''
is a valid number as well.
DECLARE @x int=1
declare @exit bit=1
WHILE @x<=len('123c') AND @exit=1
BEGIN
IF ascii(SUBSTRING('123c',@x,1)) BETWEEN 48 AND 57
BEGIN
set @x=@x+1
END
ELSE
BEGIN
SET @exit=0
PRINT 'string is not all numeric -:('
END
END
The selected answer does not work.
declare @str varchar(50)='79D136'
select 1 where @str NOT LIKE '%[^0-9]%'
I don't have a solution but know of this potential pitfall. The same goes if you substitute the letter 'D' for 'E' which is scientific notation.