Sql Server : How to test if a string has only digit characters
For a quick and efficient way to check if a string consists only of digits in SQL Server, we use the LIKE
operator with the pattern '%[^0-9]%'
to catch any non-digit characters. Here’s an out-of-the-box example:
This snippet checks whether @TestString
is armored with numbers only, thanks to our pattern [^0-9]
that flags any non-numeral intruder.
Deep Dive: Under the hood of Character Check
The ISNUMERIC Stumbling Block
While ISNUMERIC
might look promising for our digit-check task, it's a wolf in sheep's clothing. It considers strings with currency symbols, +
, -
signs, and periods (that represent decimal points) as numeric. Hence, it yields you a bucketful of false positives. Here's a demo:
That's clearly not what we're aiming at, since our goal is to find digits only.
Tackling Edge Cases: Be wary of the Empty Strings and Whitespaces
Pairing NOT LIKE
with an extra empty or whitespace string check can improve accuracy, just like adding a sidekick to Batman:
This ensures we skim off those corner cases that might play hide and seek otherwise.
Advanced Techiques: Precision Queries with Alternate Tools
The Adventure of PATINDEX
Hound of Baskerville or LIKE
is not your only option, you also have PATINDEX
. Here’s how it would look:
T-SQL Marvels: Patterns and Advanced Queries
You can use T-SQL to check based on patterns. Let's steal an idea from the Three Musketeers and all check together:
This bit of wizardry uses a tally table to independently investigate each character in the string.
Culture Shock: Numbers can be Deceptive
Numbers can dress differently in different locales with commas(,) or periods(.) as thousand separators or decimal points. For digits-only checks, commas and periods should be treated as intruders, just like non-digit characters.
Was this article helpful?