views:

35

answers:

4

How to sort this data in sql server as Pre-OP 1, Pre-Op 2 like wise

Pre-OP 1
Pre-OP 10
Pre-OP 11
Pre-OP 12
Pre-OP 13
Pre-OP 14
Pre-OP 15
Pre-OP 16
Pre-OP 17
Pre-OP 18
Pre-OP 19
Pre-OP 2
Pre-OP 20
Pre-OP 21
Pre-OP 22
Pre-OP 23
Pre-OP 24
Pre-OP 25
Pre-OP 26
Pre-OP 27
Pre-OP 28
Pre-OP 29
Pre-OP 3
Pre-OP 30
Pre-OP 4
Pre-OP 5
Pre-OP 6
Pre-OP 7
Pre-OP 8
Pre-OP 9
+1  A: 

I got an answer after doing a little bit of work so would like to share with you all, what are the flaws in this query. Please let me know

select room from m_room order by len(room), room
Shantanu Gupta
+1  A: 

ORDER BY CAST(REPLACE(str, 'Pre-OP ', '') AS INT)

Will A
@Will: that's to a good solution. But is it possible to make it string independent as I will be containing data for Pre-Op, OP, OR etc only changing part will be number rest will remain same
Shantanu Gupta
A: 

Do the sorting on the substring. It will be like Select * from Table1 order by Cast(SUBSTRING(ColumnName, 7) as INT) ASC.

Kangkan
+1  A: 

If data have a space between number and text, you can use the following:

order by cast(right(col,CHARINDEX(' ',reverse(col))) as int)
msi77
@msi: this is a much better solution than all other i feel
Shantanu Gupta