SQL Server : How to test if a string has only digit characters

后端 未结 7 1577
误落风尘
误落风尘 2021-02-05 00:59

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.

相关标签:
7条回答
  • 2021-02-05 01:14

    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.

    0 讨论(0)
  • 2021-02-05 01:20

    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
    
    0 讨论(0)
  • 2021-02-05 01:22

    Use Not Like

    where some_column NOT LIKE '%[^0-9]%'
    

    Demo

    declare @str varchar(50)='50'--'asdarew345'
    
    select 1 where @str NOT LIKE '%[^0-9]%'
    
    0 讨论(0)
  • 2021-02-05 01:23

    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.

    0 讨论(0)
  • 2021-02-05 01:28
    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
    
    0 讨论(0)
  • 2021-02-05 01:28

    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.

    0 讨论(0)
提交回复
热议问题