SQL SERVER – Validating Positive Integer Strings with Explicit Boundaries

To Validate Natural integer strings, I define a nonempty positive ASCII-digit contract. A customer wanted a simpler validator.

A nonempty uniform bead strand fits a tray while empty and mismatched candidates remain separate.

-- Function definition for an approved target database, SQL Server 2016 SP1+.
CREATE OR ALTER FUNCTION dbo.udf_IsPositiveNaturalNumber (@Number varchar(100))
RETURNS bit
AS
BEGIN
    RETURN CASE WHEN DATALENGTH(@Number) > 0
        AND @Number COLLATE Latin1_General_100_BIN2 NOT LIKE '%[^0-9]%'
        AND @Number COLLATE Latin1_General_100_BIN2 LIKE '%[1-9]%'
        THEN 1 ELSE 0 END;
END;
GO
SELECT v.TestValue, dbo.udf_IsPositiveNaturalNumber(v.TestValue) AS IsPositiveNatural
FROM (VALUES ('999'),('-999'),('abc'),('9+9'),('$9.9'),('SQLAuthority'),
             ('0'),('000'),('001'),(''),('9 '),(CAST(NULL AS varchar(100)))) v(TestValue);

My original digit-only test accepted zero and an empty string. This version requires at least one digit from 1 through 9. It rejects signs, punctuation, spaces and NULL, while permitting leading zeros. Use TRY_CONVERT when the target integer range also matters.

Historical output for the original six examples. It does not demonstrate the newly added zero, empty-string or NULL cases.
Historical output for the original six examples. It does not demonstrate the newly added zero, empty-string or NULL cases.

Binary collation makes the ASCII rule explicit. The varchar(100) parameter defines a length contract. Check longer inputs before conversion or truncation. CREATE OR ALTER requires a supported engine and permission; the companion checks the expression without creating a function.

Related reading

A valid digit representation is not proof of integer range, it is text that meets an explicit input contract.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Function, SQL Scripts, SQL Server, SQL String
Previous Post
SQL to MongoDB: Mapping SELECT, WHERE, GROUP BY and JOIN
Next Post
SQL SERVER – Fix Error: Currently This Report Does Not Have Any Data to Show, Because Default Trace Does Not Contain Relevant Information

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.