create table t1(id int identity(1,1),parentid int,level int)
insert t1
select 0, 1 union all
select 0, 1 union all
select 1, 2 union all
select 1, 2 union all
select 2, 2 union all
select 3, 3
if exists(select 1 from sysobjects where id=object_id(N'f_getlevel') and xtype='TF')
drop function f_getlevel
go
create function f_getlevel(
@level int
)returns @re table([id] int,[level] int)
as
begin
declare @l int
set @l=@level
insert @re select [id],@level from t1 where [level]=@level --and [pid]<>0
while @@rowcount>0
begin
set @l=@l-1
insert @re select a.parentid,@l
from t1 a,@re b
where a.[id]=b.[id] and b.[level]=@l+1 and a.parentid<>0
end
return
end
go
delete a from t1 a,f_getlevel(3) b where a.[id]=b.[id]