Identify Valid Numeric Expressions in SQL Server

Sometimes the solution to a weird ‘looking’ problem lies in simple SQL Server functions!

I was recently analyzing data of a SQL Server table with a varchar column that contained both numbers and alphabets. The client however now wanted to filter out the rows that contained only numbers in them. Here’s how the requirement was solved

DECLARE @TT table
(
ProductID int,
CodeIdentification varchar
)

-- Create Sample Data
INSERT INTO @TT VALUES ( 101, 'A2')
INSERT INTO @TT VALUES ( 203, '2');
INSERT INTO @TT VALUES ( 305, '2');
INSERT INTO @TT VALUES ( 403, '3');
INSERT INTO @TT VALUES ( 553, 'B3');
INSERT INTO @TT VALUES ( 634, '3');
INSERT INTO @TT VALUES ( 744, '3');
INSERT INTO @TT VALUES ( 838, '4');
SELECT * FROM @TT WHERE IsNumeric(CodeIdentification) = 1

The IsNumeric function determines if the expression passed to it is valid, by returning 1; else it returns 0

The output on running the above query is as shown below:

image


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

1 comment:

Unknown said...

Note that isnumeric() is not fully reliable

Read this
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/enhanced-isnumeric-function.aspx

Madhivanan