I want to determine if a value is integer (like TryParse
in .NET). Unfortunatelly ISNUMERIC
does not fit me because I want to parse only integers and not every kind of number. Is there such thing as ISINT
or something?
Here is some code to make things clear. If MY_FIELD
is not int, this code would fail:
SELECT @MY_VAR = CAST(MY_FIELD AS INT)
FROM MY_TABLE
WHERE MY_OTHER_FIELD = 'MY_FILTER'
Thank you
Sometimes you don't get to design the database, you just have to work with what you are given. In my case it's a database located on a computer that I only have read access to which has been around since 2008.
I need to select from a column in a poorly designed database which is a
varchar
with numbers 1-100 but sometimes a random string. I used the following to get around it (although I wish I could have re designed the entire database).Why not just do something like:
Here's a blog post describing the creation of an
IsInteger
UDF.Basically, it recommends adding
'.e0'
to the value and usingIsNumeric
. In this way, anything that already had a decimal point now has two decimal points, causingIsNumeric
to be false, and anything already expressed in scientific notation is invalidated by thee0
.In his article Can I convert this string to an integer?, Itzik Ben-Gan provides a solution in pure T-SQL and another that uses the CLR.
Which solution should you choose?
If you only want to maintain T-SQL, then use the pure T-SQL solution. If performance is more important than convenience, then use the CLR solution.
The pure T-SQL Solution is tricky. It combines the built-in ISNUMERIC function with pattern-matching and casting to check if the string represents an int.
The T-SQL part of the CLR solution is simpler. You call the fn_IsInt function just like you would call ISNUMERIC.
The C# part is simply a wrapper for the .NET's parsing function Int32.TryParse. This works because the SQL Server int and the .NET Int32 are both 32-bit signed integers.
Please read Itzik's article for a full explanation of these code samples.
Use PATINDEX
reference http://www.intellectsql.com/post-how-to-check-if-the-input-is-numeric/
With sqlserver 2005 and later you can use regex-like character classes with LIKE operator. See here.
To check if a string is a non-negative integer (it is a sequence of decimal digits) you can test that it doesn't contain other characters.
Note1: This will return empty strings too.
Note2: Using
LIKE '%[0-9]%'
will return any string that contains at least a digit.See fiddle