存储在varchar中的SQL Server混合数据类型中的自定义排序顺序

Mil*_*ean 6 sql-server sorting sql-server-2008

我有这个

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;
Run Code Online (Sandbox Code Playgroud)

哪个输出

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
Run Code Online (Sandbox Code Playgroud)

但我想要输出顺序

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
Run Code Online (Sandbox Code Playgroud)

(注意N/A是"魔术"并且总是最大的,"版本"(ex 1.2.3)总是有3位数,尽管一个或多个数字可以是char x以表示"任何数字",应始终被视为最大可能数字)

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

Mik*_*son 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
Run Code Online (Sandbox Code Playgroud)