Saturday, February 6, 2010

Sort on Alphanumeric values

I have seen so many post where developers face problem in sorting the data on alphanumeric values.The most simpls way to do is to use Isnumeric function (applicable for SQL 2005 and beyond).
Here is one of the solutions.

Declare @tbl as table(id int identity(1,1),value varchar(10))
insert into @tbl
select '123AS' union all
select '1245' union all
select 'ABC123AS' union all
select 'WE123AS' union all
select 'AS123AS' union all
select '123AS' union all
select '1'

select * from @tbl
order by isnumeric(value)desc,len(value)

The order will be descending on pure numeric values .

If you need it to be ascending then simply use

select * from @tbl
order by isnumeric(value),len(value) desc

No comments:

Post a Comment