-----建表
create table staff(id int,managerid int)
create table newtable(ID int,[Path] varchar(100))
----------所有id
create proc allid
as
begin
declare @nid int
declare cursor_id cursor for select id from staff
open cursor_id
fetch next from cursor_id into @nid
while(@@fetch_status=0)
begin
exec ppp @nid,@nid
fetch next from cursor_id into @nid
end
close cursor_id
deallocate
cursro_id
end
----------------单个id执行
create proc ppp
(@id int,@child_id int)
as
begin
declare @managerid int
select @managerid=managerid from staff where id=@child_id
if not exists(select 1 from newtable where ID=@id)
begin
select 1
insert into newtable(ID,[Path])
values(@id,cast(@id as varchar))
end
if(@managerid is null)
select 2
else
begin
select 3
update newtable set [Path]=[Path]+','+cast(@managerid as varchar) where ID=@id
exec ppp @id,@managerid
end
end