SQL Server 2012查询帮助将父项和子项提升到第n级层次结构

时间:2016-03-05 02:47:23

标签: sql-server tsql sql-server-2012

我需要一个查询来获得父母,孩子,大孩子,伟大的孩子等关系,达到第n级,可能超过100级。

以下是样本数据..

表:parentmaster

ID     Name
---- ----------
8571 File/sam 
5475 Folder/Pat
6808 path/test 
7591 file/test2
4485 Pr/dsn/ 

表:Tree

Parent child  
------ ------
8571 5475 
8571 6808 
8571 7591 
5475 4485 

预期产出:

表:Treedesc

Parent child    Parentchildtree 
------ -----    ----------------  
8571 5475       File/sam-->Folder/Pat
8571 6808       File/sam-->path/test
8571 7591       File/sam-->file/test2
5475 4485       File/sam-->Folder/Pat-->Pr/dsn/ 

感谢您的提前帮助

1 个答案:

答案 0 :(得分:0)

declare @t table (id int, name varchar(50));
insert into @t values
(8571, 'File/sam' ),
(5475, 'Folder/Pat'),
(6808, 'path/test' ),
(7591, 'file/test2'),
(4485, 'Pr/dsn/' );

declare @b table (p int, c int);
insert into @b values
(8571, 5475),
(8571, 6808), 
(8571, 7591), 
(5475, 4485);

with t as (
  select
    a.id, 0 level, a.id orig, a.name
  from
    @t a
  union all
  -- recurive query
  select
    b.p, u.level + 1, u.orig, y.name
  from
    @b b
    join @t y on y.id = b.p
    join t u on u.id = b.c
)
select
  t.id Parent
  ,t.orig child
  -- aggregative concat
  ,stuff((select ' =- ' + name as [text()]
   from t a
   where a.orig = t.orig
   order by a.level desc
   for xml path('')
  ), 1, 4, '') Parentchildtree
from
  t t
where
  -- take result with max level to exclude intermediate result
  not exists(
    select * from t h where h.orig = t.orig and h.level > t.level
  )
group by
  t.id, t.orig

输出:

enter image description here