请教一个递归的问题用存储过程如何实现。

表结构:
T_Master:
Bh bigint(8) PK //节点编号
Label varchar(50) //节点名称
ParentBh bigint(8) //父节点编号

由这个表建的一个棵树结构,层次用节点编号和父节点编号控制

我想写一个存储过程,传入一个任意节点的编号,返回该节点下所有节点的表。

不知可否实现?
谢谢!

---------------------------------------------------------------

oops, sorry, switch insert and set:

select * into temptable from T_Master where 1 = 2

alter table temptable add depth int
go

declare @node bigint
declare @depth int

set @node = 123 --指定节点编号
set @depth = 1

insert into temptable select *, @depth from T_Master Where ParentBh = @node

while @@ROWCOUNT > 0
begin
set @depth = @depth + 1

insert into temptable
select *, @depth
from T_Master Where ParentBh in (select Bh from temptable WHERE depth=@depth-1)

end

select * from temptable

drop table temptable

---------------------------------------------------------------

这样:

declare @a table (TC_Id int,TC_PID int,TC_Name varchar(200))
insert @a values(1,0,'中国')
insert @a values(2,0,'美国')
insert @a values(3,0,'加拿大')
insert @a values(4,1,'北京')
insert @a values(5,1,'上海')
insert @a values(6,1,'江苏')
insert @a values(7,6,'苏州')
insert @a values(8,7,'常熟')
insert @a values(9,6,'南京')
insert @a values(10,6,'无锡')
insert @a values(11,2,'纽约')
insert @a values(12,2,'旧金山')

declare @tmp1 table (TC_Id int,TC_PID int,TC_Name varchar(200),lev int)
insert @tmp1 select ,1 from @a where tc_ID=1
while exists(select 1 from @a a,@tmp1 b where a.tc_pid=b.tc_ID and a.tc_ID not in (select tc_ID from @tmp1))
insert @tmp1 select a.
,1 from @a a,@tmp1 b where a.tc_pid=b.tc_ID and a.tc_ID not in (select tc_ID from @tmp1)
select * from @tmp1

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus