How to get if a string is a number in T-SQL

后端 未结 7 1912
一向
一向 2021-01-17 12:57

Is there an easy way to get if string is an integer number (consists only of digits) in MS SQL 2005?

Thank you for your help.

相关标签:
7条回答
  • 2021-01-17 13:03

    You could use the LIKE operator:

    WHERE str NOT LIKE '%[^0-9]%'
    
    0 讨论(0)
  • 2021-01-17 13:11

    It is a little tricky to guarantee that a value will conform to a 4 byte integer.

    Since you are using 2005 - One way is to try to convert the value within a try/catch block. That would be the best way to insure that it is actually an int. Of course you need to handle the cases when it does not in the catch block according to your requirements.

    Another way to just test for only "digits" is this:

    where strVal not like '%[^0-9]%'

    That will miss -25. as well as allow '99999999999999999999' So you may need to include additional criteria with this method.

    0 讨论(0)
  • 2021-01-17 13:14

    See this:

    CREATE Function dbo.IsInteger(@Value VarChar(18))
    Returns Bit
    As 
    Begin
    
      Return IsNull(
     (Select Case When CharIndex('.', @Value) > 0 
                  Then Case When Convert(int, ParseName(@Value, 1)) <> 0
                            Then 0
                            Else 1
                            End
                  Else 1
                  End
          Where IsNumeric(@Value + 'e0') = 1), 0)   
    
    End
    
    0 讨论(0)
  • 2021-01-17 13:15

    Standart T-SQL function ISNUMERIC ( expression ) Determines whether an expression is a valid numeric type.

    0 讨论(0)
  • 2021-01-17 13:18

    The function ISNUMERIC returns whether a string is numeric, but will return true for non-integers.

    So you could use:

    WHERE ISNUMERIC(str) AND str NOT LIKE '%.%' AND str NOT LIKE '%e%' AND str NOT LIKE '%-%'
    
    0 讨论(0)
  • 2021-01-17 13:23

    Using ~(CAST(PATINDEX('%[^0-9]%', value) as BIT)) handles all the characters

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