如何创建递归查询以返回展平的连接字符串列

sha*_*651 5 sql-server-2008

我正在使用SQL Server 2008并且遇到过我从未遇到的SQL挑战.请考虑下表,该表代表层次结构类别列表:

ID  Name            Description                     ParentID
--- --------------- ------------------------------- --------
1   Bicycle         Bicycles and Tricycles          {null}
2   Wheels          Wheels                          1
3   Spoked          Spoked Wheels                   2
4   Skate Boards    Skate Boards and accessories    {null}
5   Wheels          Skate Board Wheels              4
6   Polyurethane    Polyurethane Wheels             5
Run Code Online (Sandbox Code Playgroud)

结果我正在寻找:

ID  Heirarchy                               Description
--- --------------------------------------- ------------------------------------
1   Bicycle                                 Bicycles and Tricycles
2   Bicycle, Wheels                         Wheels
3   Bicycle, Wheels, Spoked                 Spoked Wheels
4   Skate Boards                            Skate Boards and accessories
5   Skate Boards, Wheels                    Skate Board Wheels
6   Skate Boards, Wheels, Polyurethane      Polyurethane Wheels
Run Code Online (Sandbox Code Playgroud)

我想查询此表并通过将每个父项的名称连接到子项来返回表示层次结构的每一行的名称.层次结构没有预先设置的嵌套深度,我希望能够在单个查询中运行它.如何实现这一目标?

小智 3

with tree as (
   select id, 
          cast(name as varchar(max)) as hierarchy,
          name, 
          description
   from the_table
   where parentID is null
   union all
   select c.id, 
          p.hierarchy + ', ' + c.name,
          c.name,
          c.description
    from the_table c
       join tree p on p.id = c.parentID
) 
select * 
from tree;
Run Code Online (Sandbox Code Playgroud)