在sql中通过DFS搜索排序自引用表

时间:2014-10-23 07:13:28

标签: sql sql-server tsql sql-server-2012

我有一个自引用表,代表下面的一些数据:

    declare @table table( 
    ID int,
    ParentID int,
    Name varchar(50),
    levelNode int
)
declare @Temptable table( 
    ID int,
    ParentID int,
    Name varchar(50),
    levelNode int
)
declare @maxlevel int

insert into @table (ID,ParentID,Name,levelNode) select 11,null,'A',1
insert into @table (ID,ParentID,Name,levelNode) select 12,11,'B-1',2
insert into @table (ID,ParentID,Name,levelNode) select 13,11,'B-2',2
insert into @table (ID,ParentID,Name,levelNode) select 14,12,'B-1-1',3
insert into @table (ID,ParentID,Name,levelNode) select 15,12,'B-1-2',3
insert into @table (ID,ParentID,Name,levelNode) select 16,12,'B-1-3',3
insert into @table (ID,ParentID,Name,levelNode) select 17,13,'B-2-1',3
insert into @table (ID,ParentID,Name,levelNode) select 18,13,'B-2-2',3
insert into @table (ID,ParentID,Name,levelNode) select 19,13,'B-2-3',3
insert into @table (ID,ParentID,Name,levelNode) select 20,19,'B-2-3-1',4
insert into @table (ID,ParentID,Name,levelNode) select 21,19,'B-2-3-2',4
insert into @table (ID,ParentID,Name,levelNode) select 22,17,'B-2-1-1',4
insert into @table (ID,ParentID,Name,levelNode) select 23,17,'B-2-1-2',4

declare @ID int
select @ID=11;
With ret AS(
    select * from @table
    where ID=@ID
    union all
    select t.* from @table t inner join ret r ON t.ParentID=r.ID 
)

insert into @Temptable select * from ret where ID<>@ID
order by ??????????????????

select * from @Temptable

enter image description here

我想这样订购:

enter image description here

我应该按节顺序写什么!

1 个答案:

答案 0 :(得分:0)

试试这个..

Fiddle demo

INSERT INTO @Temptable 
SELECT * 
FROM   ret 
WHERE  id <> @ID 
ORDER  BY Substring(NAME, 3, 1), 
          Substring(NAME, 5, 1), 
          Substring(NAME, 7, 1)