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

猜你喜欢

转载自blog.csdn.net/tomstars/article/details/80935935