SQL – How To Check If A String Contains Numbers

Use the PATINDEX function to check for an integer value continued in the string.

If PATINDEX returns a value greater than 0 then the string does contain an integer, you can use PATINDEX to determine the position of the integer within the string.

If PATINDEX is not greater than zero then the string does not contain an integer value.

DECLARE @string varchar(50)
SET @string = ‘this is a string with numb3rs in it’

IF PATINDEX(‘%[0-9]%’,@string) > 0 
      PRINT ‘YES, The string has contains the number ‘ +
                  substring(@string,PATINDEX(‘%[0-9]%’,@string),1) +
                  ‘ at position ‘ +
                  cast(PATINDEX(‘%[0-9]%’,@string) as char)
ELSE 
      PRINT ‘NO, The string does not have numbers’

Advertisements

2 thoughts on “SQL – How To Check If A String Contains Numbers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s