SQL Interview: 44 Test for an integer value

This is a post in the SQL Interview series. These aren’t trick or gotcha questions, they’re just questions designed to scope out a candidate’s knowledge around SQL Server and Azure SQL Database.
Section: Developer Level: Medium
Question:
You have a value in a variable named @NewValue. The data type is varchar(20).
You want to check if the value in the string is an integer and could be cast to an integer.
What is the best way to do that?
Answer:
While many people will use ISNUMERIC() for this type of purpose, it returns 1 for a wide variety of numeric values, including many that would surprise most users.
Instead of using ISNUMERIC(), you should use TRY_CAST() to test values for a target data type.
-- Instead of
IF ISNUMERIC(@NewValue) = 1
-- Use this
IF TRY_CAST(@NewValue AS int) IS NOT NULL
2025-05-06