2012-07-24 142 views
1

我刚刚在下午发现了CTE,在2个小时内享用CTE后,我意识到他们没有执行像我们所有其他语言学到的常见递归。与CTE真正的递归?

我的意思是,我总是看到像树搜索递归。所以我期待CTE一路走下去找到它的第一片叶子,但是没有。他分层次工作。它从头部开始,然后是所有的分支,然后是所有的分支,等等......然后是叶子。

有没有办法让它的搜索方式不同?也许我错过了什么......我 SQL Server上运行2005

(非,我不能在2008年改变)为了把事情说清楚,我不想:

  1. TEAM1
  2. TEAM2
  3. team3
  4. team1-1
  5. team3-1
  6. team1-2

  1. TEAM1
  2. team1-1
  3. team1-2
  4. TEAM2
  5. team3
  6. team3-1

感谢

+4

的'ORDER BY'条款浮现在脑海。除非您指定它,否则CTE不会改变您没有*保证*任何特定顺序的事实。 – 2012-07-24 17:49:16

回答

7

当您进行递归时,您可以构建一个列进行排序。

事情是这样的:

declare @t table 
(
    ID int, 
    ParentID int, 
    Name varchar(10) 
); 

insert into @T values 
(1, null, 'team1'), 
(2, null, 'team2'), 
(3, null, 'team3'), 
(4, 1, 'team1-1'), 
(5, 1, 'team1-2'), 
(6, 3, 'team3-1'); 

with C as 
(
    select T.ID, 
     T.ParentID, 
     T.Name, 
     cast(right(100000 + row_number() over(order by T.ID), 5) as varchar(max)) as Sort 
    from @T as T 
    where T.ParentID is null 
    union all 
    select T.ID, 
     T.ParentID, 
     T.Name, 
     C.Sort+right(100000 + row_number() over(order by T.ID), 5) 
    from @T as T 
    inner join C 
     on T.ParentID = C.ID 
) 
select * 
from C 
order by Sort 

结果:

ID   ParentID Name  Sort 
----------- ----------- ---------- ------------ 
1   NULL  team1  00001 
4   1   team1-1 0000100001 
5   1   team1-2 0000100002 
2   NULL  team2  00002 
3   NULL  team3  00003 
6   3   team3-1 0000300001 
+0

感谢您的提示。我明天会检查一下。 – Gloups 2012-07-24 18:57:51

+0

完美,这很好,谢谢你的快速帮助;) – Gloups 2012-07-26 09:25:28

+0

不客气。 – 2012-07-26 09:25:42