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".