views:

107

answers:

5

Hello.

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.

+1  A: 

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
Anton Gogolev
+1  A: 

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 '%-%'
Paul
A: 

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

Dewfy
Valid numeric type indeed, though it doesn't care about whether integer, decimal, money or float. And the OP explicitly asked about integer.
Joey
A: 

You could use the LIKE operator:

WHERE str NOT LIKE '%[^0-9]%'
Paul
A: 

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.

TG