Click here to Skip to main content
15,909,747 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I need to use order by for alphanumeric. i have 3 fields namely

NAS9998
NAS9999
NAS10000

when i give order by it shows NAS10000 in first. How can i solve this.

please help me

Thanks

Afsal
Posted

SQL
Create table ##Table(id bigint identity(1,1),code nvarchar(max))

insert Into ##Table(code)values('NAS9998')
insert Into ##Table(code)values('NAS9999')
insert Into ##Table(code)values('NAS10000')

select * From ##Table order by Cast(substring(code,4,100) as bigint) ASC
 
Share this answer
 
Comments
afsal.mp 6-May-14 9:04am    
Thank you very much.. this is the answer i was waiting for.......
King Fisher 6-May-14 9:09am    
welcome :)
Maciej Los 6-May-14 9:29am    
5ed!
Yes, you can. In case you want to sort by numbers, you need to extract numeric part, for example:
SQL
SELECT FieldName, LEFT(FieldName, 3) AS FirstPart, CONVERT(INT, RIGHT(FieldName, LEN(FieldName)-3)) AS SecondPart
FROM TableName
ORDER BY  CONVERT(INT, RIGHT(FieldName, LEN(FieldName)-3)) ASC
 
Share this answer
 
v2
Comments
afsal.mp 6-May-14 8:59am    
i am getting this error "Invalid length parameter passed to the RIGHT function."
Maciej Los 6-May-14 9:06am    
Do you have NULL's?<br>
If yes, add WHERE statement before ORDER BY line: WHERE FieldName IS NOT NULL<br>
King Fisher 6-May-14 9:27am    
the above solution is Working Pakka
just Replace fieldname as code and Table name as ##table

Maciej Los 6-May-14 9:28am    
Thanks for support ;)
King Fisher 6-May-14 9:31am    
i'm big fan of you .no thanks ;)

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