5

我正在使用 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

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

4

1 回答 1

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;
于 2012-11-29T23:11:28.467 回答