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
WHERE IsNumeric(MY_FIELD) = 1 AND CAST(MY_FIELD as VARCHAR(5)) NOT LIKE '%.%'
That is probably the simplest solution. Unless your MY_FIELD
contains .00 or something of that sort. In which case, cast it to a float to remove any trailing .00s
As of SQL Server 2012, the TRY_CONVERT
and TRY_CAST
functions were implemented. Thise are vast improvements over the ISNUMERIC
solution, which can (and does) give false positives (or negatives). For example if you run the below:
SELECT CONVERT(int,V.S)
FROM (VALUES('1'),
('900'),
('hello'),
('12b'),
('1.1'),
('')) V(S)
WHERE ISNUMERIC(V.S) = 1;
Using TRY_CONVERT
(or TRY_CAST
) avoids that:
SELECT TRY_CONVERT(int,V.S),
V.S,
ISNUMERIC(V.S)
FROM (VALUES('1'),
('900'),
('hello'),
('12b'),
('1.1'),
('')) V(S)
--WHERE TRY_CONVERT(int,V.S) IS NOT NULL; --To filter to only convertable values
Notice that '1.1'
returned NULL
, which cause the error before (as a string represtation of a decimal cannot be converted to an int
) but also that ''
returned 0
, even though ISNUMERIC
states the value "can't be converted".
I think that there is something wrong with your database design. I think it is a really bad idea to mix varchar and numbers in one column? What is the reason for that?
Of course you can check if there are any chars other than [0-9], but imagine you have a 1m rows in table and your are checking every row. I think it won't work well.
Anyway if you really want to do it I suggest doing it on the client side.
I am not a Pro in SQL but what about checking if it is devideable by 1 ? For me it does the job.
SELECT *
FROM table
WHERE fieldname % 1 = 0
This works fine in SQL Server
SELECT (SELECT ISNUMERIC(2) WHERE ISNUMERIC(2)=1 AND 2 NOT LIKE '%.%')
See whether the below query will help
SELECT *
FROM MY_TABLE
WHERE CHARINDEX('.',MY_FIELD) = 0 AND CHARINDEX(',',MY_FIELD) = 0
AND ISNUMERIC(MY_FIELD) = 1 AND CONVERT(FLOAT,MY_FIELD) / 2147483647 <= 1