2012-04-23 64 views
6

我有這個自定義排序順序存儲在一個varchar

declare @testtable table (test nvarchar(max)) 


insert into @testtable (test) values ('1.2.3') 
insert into @testtable (test) values ('1.20.3') 
insert into @testtable (test) values ('1.19.x') 
insert into @testtable (test) values ('1.x.x') 
insert into @testtable (test) values ('1.19.3') 
insert into @testtable (test) values ('DEC09') 
insert into @testtable (test) values ('Plutonium') 
insert into @testtable (test) values ('dec09') 
insert into @testtable (test) values ('N/A') 
insert into @testtable (test) values ('MyTest20') 
insert into @testtable (test) values ('20MyTest') 
insert into @testtable (test) values ('1.4.18') 
insert into @testtable (test) values ('1.4.168') 

select * from @testtable 
order by test asc; 

其輸出

1.19.3 
1.19.x 
1.2.3 
1.20.3 
1.4.168 
1.4.18 
1.x.x 
20MyTest 
DEC09 
dec09 
MyTest20 
N/A 
Plutonium 

但我想輸出爲了

1.2.3 
1.4.18 
1.4.168 
1.19.3 
1.19.x 
1.20.3 
1.x.x 
20MyTest 
DEC09 
dec09 
MyTest20 
Plutonium 
N/A 

(注意N/A是「魔術」並且總是最大,「版本」(例如1.2.3)總是有3位數,儘管一個或多個數字可能是char x指示「任何數字」,這應該始終被認爲是最大可能的數字)

如何在SQL Server中完成此操作?

+2

+ 1用於DDL和INSERT。哪個SQL Server版本? – 2012-04-23 09:41:47

+0

這個版本是不同的,因爲解決方案將被放置在不同的服務器上 – Millerbean 2012-04-23 10:55:00

+0

* How *不同?你想要運行的最早版本是什麼?請添加適當的標籤。 – 2012-04-23 13:09:46

回答

3
select TT.* 
from @testtable as TT 
order by case when TT.test = 'N/A' then 1 else 0 end, 
     case when isnumeric(parsename(test, 3)+'E+00') = 1 then cast(parsename(test, 3) as int) else 99999 end, 
     case when isnumeric(parsename(test, 2)+'E+00') = 1 then cast(parsename(test, 2) as int) else 99999 end, 
     case when isnumeric(parsename(test, 1)+'E+00') = 1 then cast(parsename(test, 1) as int) else 99999 end, 
     test 
+1

偉大的解決方案,但有一點是該列是一個varchar,將被排序爲一個varchar。您可能會考慮使用此解決方案來完成此操作:http://stackoverflow.com/a/119842/326923 – 2012-04-23 10:54:26

+0

這給我與我自己發佈的上面相同的結果 – Millerbean 2012-04-23 12:30:33

+0

1.4.168需要與1.4交換。18,所以仍然不是100%:-) – Millerbean 2012-04-23 12:39:06

0

這應該很容易。

創建2列的新表:

OrderValue串

DESCR字符串

的順序值你想

A- 1.2.3

b將 - 1.4.18

c- 1.4.168

D- 1.19.3

E-1.19.x

F-1.20.3

G- 1.XX

H- 20MyTest

I-09年12月

j-dec09

K- MyTest20

1-鈈

間 - N/A

現在加入TestTable的與由 「OrderValue」

即它這個新表和順序