A real recursion with CTE?

后端 未结 1 1074
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 09:02

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 languag

相关标签:
1条回答
  • 2020-12-06 09:18

    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
    
    0 讨论(0)
提交回复
热议问题