一个树状表:TB
字段名: 编号 名称 上级编号查询要求,根据一个编号值查询它的所有的子树节点。declare @temp table (编号 int)
insert @temp
select 编号 from tb where 上级编号=给定编号while exists (select 编号 from tb where 上级编号 in (select 编号 from @temp) and 编号 not in (select 编号 from @temp))
insert @temp
select 编号 from tb where 上级编号 in (select 编号 from @temp)
and 编号 not in (select 编号 from @temp)select * from tb where 编号 in (select 编号 from @temp)
字段名: 编号 名称 上级编号查询要求,根据一个编号值查询它的所有的子树节点。declare @temp table (编号 int)
insert @temp
select 编号 from tb where 上级编号=给定编号while exists (select 编号 from tb where 上级编号 in (select 编号 from @temp) and 编号 not in (select 编号 from @temp))
insert @temp
select 编号 from tb where 上级编号 in (select 编号 from @temp)
and 编号 not in (select 编号 from @temp)select * from tb where 编号 in (select 编号 from @temp)
create table #tmpecho (编号 varchar(100))
--保存同级别节点的临时表
create table #tmp (编号 varchar(100))
--当前级别为最高级别(即结定编号的级别)
insert into #tmp values('给定编号')
--对当前级别进行循环,处于当前级别的节点还有子节点时,置其子节点所在级别为当前级别
while @@rowcount<>0
begin
drop table #tmp
select 编号 into #tmp from TB where 上级编号 in (select 编号 from #tmp)
--得到当前级别的子节点
insert into #tmpecho select * from #tmp
enddrop table #tmp
select * from #tmpecho
drop table #tmpecho将上面语句改写,可得到所有子孙及每个子孙是给定编号的第几级子孙