1. 程式人生 > >sqlserver通過遞迴查詢所有下級或上級部門和使用者

sqlserver通過遞迴查詢所有下級或上級部門和使用者

查詢當前使用者所在部門的所有下級包括當前部門

with cte as
(
    select Id,Pid,DeptName, 0 as lvl from Department
    where Id = 2
    union all
    select d.Id,d.Pid,d.DeptName,lvl + 1 from cte c inner join Department d
    on c.Id = d.Pid
)
select * from cte

查詢當前使用者所在部門的所有上級包括當前部門

with cte as
(
    select Id,Pid,DeptName, 0 as lvl from Department
    where Id = 2
    union all
    select d.Id,d.Pid,d.DeptName,lvl + 1 from cte c inner join Department d
    on c.Pid= d.Id
)
select * from cte