Click here to Skip to main content
15,908,444 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,
I am Working with Asp.net and Sql. I have the data following like this

Names
LD_B_10
LD_B_101
LD_B_2
LD_B_1
LD_B_200
LD_B_100

I am using Select Query with using order by "Names". I get the Following type of result.
LD_B_1
LD_B_10
LD_B_100
LD_B_101
LD_B_2
LD_B_200

but I need Following type of result.

LD_B_1
LD_B_2
LD_B_10
LD_B_100
LD_B_101
LD_B_200

any one give me the reference how to do it.

Thanks Advance.
Posted

Use SUBSTRING and CAST to extract the number part of your string and sort on that value.
SQL - Substring Function | 1Keydata[^]
CAST and CONVERT (Transact-SQL)[^]
 
Share this answer
 
declare @tab table(
names nvarchar(max)

)
insert into @tab
values ('LD_B_10')
,('LD_B_101')
,('LD_B_2')
,('LD_B_1')
,('LD_B_200')
,('LD_B_100')

select * from @tab order by try_convert(int,replace(Names,'ld_b_','')) asc
 
Share this answer
 
Your query will be

SQL
select   Names  from myTable order by
CAST(RIGHT(Names,len(Names)-5) AS int)


Then your Result will be:

LD_B_1
LD_B_2
LD_B_10
LD_B_100
LD_B_101
LD_B_200


Happy Coding! :)
 
Share this answer
 
Comments
Member 11889799 30-Jan-16 4:30am    
Hi Suman,
Thanks for your Response.
Anisuzzaman Sumon 30-Jan-16 5:09am    
you most welcome! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900