with cte as
(
select [DeptID],[MasterID],[DeptName],1 as lvl from Department
where [DeptID] = 55
union all
select d.[DeptID],d.[MasterID],d.[DeptName],lvl+1 from cte c inner join Department d
on c.[DeptID] = d.[MasterID]
)
select * from cte
结果:
DeptID MasterID DeptName lvl
55 0 上级领导 1
56 55 司法部检查组 2
本文展示了一个使用SQL递归查询来获取组织中部门层级结构的例子。通过使用CTE(公共表表达式)和递归联合操作,可以有效地从数据库中获取部门及其子部门的信息,形成一个层级结构。
796

被折叠的 条评论
为什么被折叠?



