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'--需要遍历的节点(开始节点)
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
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 Departmentwhere 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