如何从SQL Server上的多个值获取层次结构?

时间:2012-09-17 08:48:33

标签: sql sql-server set

我的表RD只有一列:

-----
rd_id
-----
3 
2 
6 
7 
8 

我的表DL有两列,这个表上存储了层次结构:

----------------------
dl_id     dl_parent
----------------------
1         2               
2         Null
3         Null
4         6
6         7
7         8
8         Null

现在的问题是如何使用RD表的成员从DL表中获取层次结构。 结果将是:

--------------
rd_id   dl_id
--------------
3         3

2         2

6         6
6         7
6         8

7         7
8         8

8         8

从周五开始,我一直在努力解决这个问题,但仍然无法解决问题。 我知道我可以使用公用表表达式从一个值遍历递归(例如,使用输入6创建一个函数并生成6,7,8)。 但我不知道如何使用多个值(rd_id)。

有一些想法吗?

2 个答案:

答案 0 :(得分:1)

这会产生正确的结果。数据设置:

declare @RD table (rd_id int not null)
insert into @RD(rd_id) values
(3),
(2),
(6),
(7),
(8)

declare @DL table (dl_id int not null,dl_parent int null)
insert into @DL(dl_id,dl_parent) values
(1,2),          
(2,Null),
(3,Null),
(4,6),
(6,7),
(7,8),
(8,Null)

查询:

;with AllValues as (
    select rd_id,rd_id as dl_id from @RD
    union all
    select rd_id,dl_parent
    from AllValues av
        inner join
        @DL dl
            on
                av.dl_id = dl.dl_id
    where
        dl.dl_parent is not null
)
select * from AllValues

结果:

rd_id       dl_id
----------- -----------
3           3
2           2
6           6
7           7
8           8
7           8
6           7
6           8

说明:

在CTE的锚点中,我们只需从rd_id表中选择@RD两次 - 因为您的示例意味着每个输入行都应该在两列中生成具有相同值的输出行。 / p>

然后我们根据第二列加入@DL表,找到我们可以找到的任何匹配父行。如果我们找到父级,那么我们生成一个新行,将父值替换为第二列。这将一直持续到没有生成新行。

答案 1 :(得分:0)

您必须使用动态视图来创建递归查询,如下所示:

with n as (
select dl_id, dl_id as ancestor
from dbo.dl
union all
select np1.dl_id, n.ancestor
from dl as np1 , n
where n.dl_id = np1.dl_parent)
select * from n
where dl_id in (select rd_id from rd)
order by dl_id, ancestor