Best equivalent for IsInteger in SQL Server

2019-01-07 19:17发布

What is the best way to determine whether or not a field's value is an integer in SQL Server (2000/2005/2008)?

IsNumeric returns true for a variety of formats that would not likely convert to an integer. Examples include '15,000' and '15.1'.

You can use a like statement but that only appears to work well for fields that have a pre-determined number of digits...

select * where zipcode like '[0-9][0-9][0-9][0-9][0-9]'

I could write a user defined function that attempts to convert a varchar parameter to an int within a try/catch block but I'm checking with the community to see if someone has come across any succient methods to achieve this goal - preferably one that can be used within the where clause of a SQL statement without creating other objects.

11条回答
forever°为你锁心
2楼-- · 2019-01-07 19:51

Late entry that handles negative

ISNUMERIC(zipcode + '.0e0') --integer
ISNUMERIC(zipcode + 'e0')  --decimal

For more see this

查看更多
爷、活的狠高调
3楼-- · 2019-01-07 19:52

I did it using a Case statement: Cast(Case When Quantity/[# of Days]= Cast(Quantity/[# of Days] as int) Then abs(Quantity/[# of Days]) Else 0 End as int)

查看更多
迷人小祖宗
4楼-- · 2019-01-07 19:55

To test whether the input value is an integer or not we can use SQL_VARIANT_PROPERTY function of SQL SERVER.

The following SQL Script will take input and test it whether the data type turns out to be integer or not

declare @convertedTempValue bigint, @inputValue nvarchar(255) = '1' --Change '1' to any input value
set @convertedTempValue = TRY_PARSE(@inputValue as bigint) --we trying to convert to bigint
declare @var3 nvarchar(255) = cast (SQL_VARIANT_PROPERTY(@convertedTempValue,'BaseType') as nvarchar(255)) --we using SQL_VARIANT_PROPERTY to find out datatype
if ( @var3 like '%int%')
    begin
    print 'value is integer'
    end
else
    begin
    print 'value is non integer'
    end
go
查看更多
姐就是有狂的资本
5楼-- · 2019-01-07 19:57

1 approach is

zipcode NOT LIKE '%[^0-9]%'

Double negatives, got to love 'em!

查看更多
我命由我不由天
6楼-- · 2019-01-07 19:58

After moving to sql 2008, I was struggling with isnumeric('\8') returning true but throwing an error when casting to an integer. Apparently forward slash is valid currency for yen or won - (reference http://www.louiebao.net/blog/200910/isnumeric/)

My solution was

case when ISNUMERIC(@str) > 0 and not rtrim(@str) LIKE '[^0-9]%'  and not rtrim(@str) LIKE '%[^0-9]' and not rtrim(@str) LIKE '[^0-9]%' then rtrim(@str) else null end
查看更多
男人必须洒脱
7楼-- · 2019-01-07 20:00

I came up with the perfect answer for this on another StackO question.
It also proves you cannot use ".0e0" like one user suggests here.
It does so without CLR or non-scalar functions.
Please check it out: https://stackoverflow.com/a/10645764/555798

查看更多
登录 后发表回答