SQL中的递归分层查询

时间:2018-04-11 10:49:05

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

我有下表

TblMatrix

ID   ApproverId
--------------------
1    4
2    7
7    8
4    5
5    6

我想编写一个自连接查询,以返回任何ApproverId

的输出

如果我通过ApproverId As 6

输出应为

ID
---
5
4
1

如果我通过ApproverId As 8

输出应为

ID
---
7
2

1 个答案:

答案 0 :(得分:3)

使用递归查询

with rcte as
(
    select id from tblMatrix where approverId = 8
    union all
    select tblMatrix.id 
    from tblMatrix
    join rcte on tblMatrix.approverid = rcte.id
)
select * from rcte

dbfiddle demo