2010-08-06 59 views
1

如何在SQL Server中此數據作爲預OP 1,預作品2一樣明智如何排序的SQL服務器字符串

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

如果數據有編號和文本之間的空間,可以使用以下命令:

order by cast(right(col,CHARINDEX(' ',reverse(col))) as int) 
+0

這是比所有其他我感覺好得多的解決方案 – 2010-08-06 09:26:50

1

我得到的回答做的工作那麼一點點會後整理喜歡與大家分享,這個查詢有哪些缺陷。請讓我知道

select room from m_room order by len(room), room 
1

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

+0

這是一個很好的解決方案。但是,是否有可能使它獨立於字符串,因爲我將包含Pre-Op,OP,OR等數據。只有更改部分將數字休息保持相同 – 2010-08-06 07:05:22

0

請在串排序。它會像Select * from Table1 order by Cast(SUBSTRING(ColumnName, 7) as INT) ASC

1

試試這個:

Order BY 
    CASE WHEN isnumeric(emp_id) = '1' THEN cast (emp_id AS int) 
     WHEN isnumeric(substring(emp_id, 3, 7))=1 THEN cast (substring(emp_id, 3, 7) AS int) 
     ELSE '99999999' 
    END