--测试数据
create table [File](id int,parentid int,filesize int)
insert [File]
select 1,0,100
union all select 2,1,75
union all select 3,1,25
union all select 4,2,50
union all select 5,2,25
union all select 6,5,20
union all select 7,6,5
go
--创建处理用的函数
create function f_child(@id int)
returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select id,@l from [File] where parentid=@id
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from [File] a join @re b on a.parentid=b.id
where b.level=@l-1
end
return
end
go
--调用实现实现处理:
--1.求出所有id号为1的所有子对象数据
select a.* from [File] a join dbo.f_child(1) b on a.id=b.id
--2、更新所有id号为1的所有子对象的filesize为0
update [File] set filesize=0
from [File] a join dbo.f_child(1) b on a.id=b.id
--创建处理用的函数
create function f_child(@id int)
returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select id,@l from [File] where parentid=@id
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from [File] a join @re b on a.parentid=b.id
where b.level=@l-1
end
return
end
go