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

时间:2012-11-29 23:06:50

标签: 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

结果我正在寻找:

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

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

1 个答案:

答案 0 :(得分: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;