日期:2014-05-17  浏览次数:20376 次

一个排序的问题,不知道要从何入手解决。

select code from tb order by code

上面的sql语句得到的结果是这样的,但是我想要的结果是。
1
1-1
1-2
1-19
1-20
2
3
4
5

结果应该要根据阿拉伯数字来排序,code可能会出现1-1-1第三个级别的情况。
请大家帮帮忙。
sql sql?order?by

------解决方案--------------------
引用:
直接你的语句还是可以的啊
--create table #tb
--(
--    code varchar(20) collate Chinese_PRC_CI_AS
--)
 
--insert into #tb 
--select '1'
--union all
--select '1-1'
--union all
--select '1-2'
--union all
--select '1-3'
--union all
--select '1-20'
--union all
--select '2-1'
--union all
--select '2-10'
--union all
--select '3-1'
--union all
--select '4-1'
--union all
--select '5-1'
 
select * from #tb
order by code

/*
code
--------------------
1
1-1
1-2
1-20
1-3
2-1
2-10
3-1
4-1
5-1
*/


这个例子不够典型。
这样:
1-1
1-2
1-3
1-11
1-20
才能区分
------解决方案--------------------

--1)創建函數
CREATE function [dbo].[GetSplitOfIndex]
(
@String nvarchar(max), --要分割的字符串
@split nvarchar(10), --分隔符号
@index int --取第几个元素
)
returns nvarchar(1024)
--returns int
as
begin
declare @location int --标记所在位置
declare @start int --标记查找开始位置
declare @next int --
declare @seed int --标记长度

set @String=ltrim(rtrim(@String))--去掉前后空格
set @start=1
set @next=1
set @seed=len(@split) --标记长度赋值

set @location=charindex(@split,@String)
while @location<>0 and @index>@next--在检索完整个字符串或者检测到所选字符串时结束循环
begin
set @start=@location+@seed
set @location=charindex(@split,@String,@start)
set @next=@next+1
END
return 
CASE 
WHEN CHARINDEX(@split,@String)>0 AND @location =0 THEN ''
WHEN CHARINDEX(@split,@String)=0 AND @location =0 THEN @String
ELSE substring(@String,@start,@location-@start)
end
end
go

--2)執行查詢
;WITH a1 (cstr) AS
(
select '1' UNION ALL
select '1-1' UNION ALL
select '1-1-1' UNION ALL
select '1-2' UNION ALL
select '1-3' UNION ALL
select '1-11' UNION ALL
select '1-20' UNION ALL
select '2' UNION ALL
select '2-1' UNION ALL
select '2-1-1' UNION ALL
select '2-2' UNION ALL<