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 a
Use TRY_CONVERT which is an SQL alternative to TryParse in .NET. IsNumeric() isn’t aware that empty strings are counted as (integer)zero, and that some perfectly valid money symbols, by themselves, are not converted to (money)zero. reference
SELECT @MY_VAR = CASE WHEN TRY_CONVERT(INT,MY_FIELD) IS NOT NULL THEN MY_FIELD
ELSE 0
END
FROM MY_TABLE
WHERE MY_OTHER_FIELD = 'MY_FILTER'
Here's a blog post describing the creation of an IsInteger
UDF.
Basically, it recommends adding '.e0'
to the value and using IsNumeric
. In this way, anything that already had a decimal point now has two decimal points, causing IsNumeric
to be false, and anything already expressed in scientific notation is invalidated by the e0
.
The following is correct for a WHERE
clause; to make a function wrap it in CASE WHEN
.
ISNUMERIC(table.field) > 0 AND PATINDEX('%[^0123456789]%', table.field) = 0
declare @i numeric(28,5) = 12.0001 if (@i/cast(@i as int) > 1) begin select 'this is not int' end else begin select 'this is int' end
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.
SELECT numstr
FROM table
WHERE numstr NOT LIKE '%[^0-9]%'
Note1: This will return empty strings too.
Note2: Using LIKE '%[0-9]%'
will return any string that contains at least a digit.
See fiddle
Why not just do something like:
CASE
WHEN ROUND(MY_FIELD,0)=MY_FIELD THEN CAST(MY_FIELD AS INT)
ELSE MY_FIELD
END
as MY_FIELD2