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 --id 部门编号,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 --id 部门编号,PID 上级部门编号
) select * from cte

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM