Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

tsql - A real recursion with CTE?

I just discovered CTE this afternoon and after enjoying them during 2 hours, I realized that they did not perform a common recursion like we all learned in any other language.

What I mean is, I always see recursion like a tree search. So i was expecting CTE to go all the way down to the first leaf it founds, but no. He works by layers. It begins by the head, then all the branches, then all the sub-branches, etc... and THEN the leaves.

Is there a way to make it search differently ? Perhaps did I miss something... I work on SQL Server 2005 (non, I can't change for the 2008)

To make things clear, I don't want :

  1. team1
  2. team2
  3. team3
  4. team1-1
  5. team3-1
  6. team1-2

but

  1. team1
  2. team1-1
  3. team1-2
  4. team2
  5. team3
  6. team3-1

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can build a column to sort by when you do the recursion.

Something like this:

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

Result:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...