在T-SQL中表示树(菜单)结构

时间:2018-03-22 21:20:48

标签: sql sql-server tsql relational-database

我有这张桌子。

id        parent
----------------
1         0 
2         0 
3         1 
4         3 
5         2

我想将它导出到一个新表的列中,看起来像这样。它将代表树(菜单)结构。因此,每个ID都有自己的行,但如果它连接到父级,则会添加四个空格以使层次结构明显。

     ID           etc...
-------------  ------------
|1          |
|    3      |
|         4 |
|2          |   
|    5      |

我只能提出一个使用游标集的解决方案,因此它取决于孩子的数量。我试图做一个递归但是真的不能想到一个解决方案,它将从一个表中获取数据,使用空格进行递归并将其导出到新表中的列。谢谢。

2 个答案:

答案 0 :(得分:3)

您可以使用递归CTE:

with cte as (
      select id, cast(id as varchar(max)) as hierarchy
      from t
      where parent = 0
      union all
      select t.id, cte.hierarchy + '-->' + cast(t.id as varchar(max))
      from cte join
           t
           on t.parent = cte.id
     )
select *
from cte;

这为层次结构提供了更加明确的格式。虽然您可以使用缩进,但我认为显式层次结构提供了更多信息。

答案 1 :(得分:0)

这是有用的

    declare @tmp table (id int, parent int)
    declare @NewTable table (id VARCHAR(50))

    insert into @tmp
    SELECT 1,0
    union
    SELECT 2,0
    union
    SELECT 3,1
    union
    SELECT 4,3
    union
    SELECT 5,2



    ;with name_tree as (
       select id,id as p1,parent
       from @tmp
       --where id = 4 -- this is the starting point you want in your recursion
       union all
       select p.id,c.id as p1, c.parent
       from @tmp c
         join name_tree p on p.parent = c.id  -- this is the recursion
    ) 



    INSERT INTO @NewTable(id)
    select REPLICATE( ' ' , (Count(*)-1)*4 )+CONVERT(VARCHAR(10),id)
    from name_tree
    group by id

    select * from @NewTable
相关问题