How to check if a string contains numbers

There are number of ways in SQL Server to check if a string has numbers in it. In one of the previous articles, we saw how to Extract Numbers from a String using Sql Server 2005

I recently got a comment on that article from a sqlservercurry.com visitor who asked me to find out if a string has numbers, using PatIndex. Here's how to do so using PatIndex :

DECLARE @str1 varchar(15)
SET @str1 = 'abcde99jtk'

-- Check if PatIndex returns a value > 0. If yes, the string has numbers
-- If the value is 0, the string does not have numbers
IF PATINDEX('%[0-9]%',@str1) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

Anonymous said...

Awesome, thanks for the post! solved it!

amirali1982 said...

thanks a lot, this query helped me with a related problem...