好象满多人需要的就写了个,需要的就自己改成存储过程吧
表test的结构
C        P
1 2
2 3
3 4
1 8
1 9
8 10
NULL 1
4 5
4 6
4 7
NULL 11set nocount ondeclare @c as int
declare @t as int
declare @p as int
declare @s as intset @s=1select * 
into #t
from test
where c not in (select isnull(p,0) from test)--select * from #tdeclare dd cursor
for select * from #t
open ddFETCH next FROM dd
into @p,@c
WHILE @@FETCH_STATUS = 0
BEGIN
--print 'P='+cast(@p as varchar(100))+'  '+'C='+cast(@c as varchar(100))
set @t=@c
while 1=1
begin
select @c=p from test where c=@c
if @c is null
begin
delete #t where c=@t
break
end
if @c=@s
begin
break
end
end
FETCH next FROM dd
into @p,@c
ENDclose dd
DEALLOCATE ddselect * from #tdrop table #t