2012-11-29 1 views
5

SQL Server 2008を使用しています。フラット化され連結された文字列を返す再帰クエリを作成するにはどうすればいいですか

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 

私はこのテーブルを照会し、階層を表すことになり、各列の名前を返したい:

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 

結果は、私が探しています:階層カテゴリリストを表し、次の表を考えてみましょう子に各親の名前を連結することによって、階層にはあらかじめ設定された入れ子の深さがありません。これを単一のクエリで実行できるようにしたいと考えています。これはどのように達成できますか?

答えて

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; 
+0

完璧に、ありがとう! – shark92651

関連する問題