SQL中的递归

create table A
(
id int,
upid int,
caption varchar(100)
)

insert A
select 1,0,'总经理办公室' union
select 2,1,'人事部' union
select 3,1,'业务部' union
select 4,3,'业务部(内)' union
select 5,3,'业务部(外)'



create proc Temp_proc(@ID int)
as
declare @T_levn int
declare @t1 table(id int,upid int,caption varchar(100),T_levn int)
set @T_levn=1
insert @t1 select A.*,@T_levn from A where A.id=@ID
while @@rowcount>0
begin
set @T_levn=@T_levn+1
insert @t1 select A.*,@T_levn from A where A.upid in (select id from @t1 where T_levn=@T_levn-1)
end
select * from @t1

exec Temp_proc 3

你可能感兴趣的:(sql)