create table tt (id int ,parentid int ,sname nvarchar(20))
insert into tt
select 1 , 0 , 'aaaa'
union select 2 , 0, 'bbbb'
union select 3 , 1, 'a1'
union select 4 , 1, 'a2'
union select 5 , 3, 'a11'
union select 6, 3, 'a12'
CREATE PROCEDURE dbo.tree
@id nvarchar(10)
AS
begin
create table #tt (id int ,parentid int ,sname nvarchar(20))
insert into #tt select * from tt where id =@Id
while @@rowcount<>0
begin
insert into #tt select * from tt a where parentid in (select id from #tt) and not exists(select 1 from #tt b where a.id=b.id and a.parentid=b.parentid )
end
select * from #tt
end
GO
declare @t table (
id int,
parentid int,
sname varchar(30),
lev int
)
declare @lev int
set @lev=0
insert @t select *,@lev from 树结构表 where id=@id
while exists ( select 1 from 树结构表 where parentid in (select id from @t where lev=@lev)
)
begin
insert @t select *,@lev+1 from 树结构表 where parentid in (select id from @t where lev=@lev)
set @lev=@Lev+1
end