SQL Server遍历组织架构树

本文介绍如何在SQL Server中有效地遍历和查询复杂的组织架构树,通过示例代码展示从根节点开始的遍历过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CREATE TABLE #tmp(--用于装载所有符合条件的记录
  deptID varchar(100),
  DeptParentID varchar(100))
CREATE TABLE #tmp1(--用于装载父节点ID
  deptID varchar(100),
  DeptParentID varchar(100))
CREATE TABLE #tmp2(--用于装载当前节点下的子节点记录
  deptID varchar(100),
  DeptParentID varchar(100))
  
declare @DeptID varchar(100)
set @DeptID='1119'--需要遍历的节点(开始节点)

  

--加载开始节点

insert into #tmp select DeptID,DeptParentID from Department
where DeptID=@DeptID
insert into #tmp1 select DeptID,DeptParentID from #tmp

--定义记录当前子节点数的变量
declare @count int
set @count=10 --随便设置一个大于零的数


while(@count>0)--当符合条件的子节点等于零时,循环结束
begin
  delete from #tmp2--清空上次遍历的子节点记录
  insert into #tmp2 select DeptID,DeptParentID from Department
            where DeptDelFlag=0 and DeptParentID in (select DeptID from #tmp1)--将符合条件的子节点记录插入#tmp2
  select @count=COUNT(*) from #tmp2 --统计当前符合条件的子节点记录
  if(@count>0)--若当前存在符合条件的子节点记录,则进行处理
  begin
    insert into #tmp select DeptID,DeptParentID from #tmp2--追加当前符合条件的子节点记录
    delete from #tmp1--清空父节点表
    insert into #tmp1 select DeptID,DeptParentID from #tmp2--将当前符合条件的子节点记录插入#tmp1,作为下一轮遍历的父节点
  end
end

select * from Department where DeptID in (select DeptID from #tmp)

drop table #tmp1
drop table #tmp2
drop table #tmp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值