注册 登录
编程论坛 SQL Server论坛

SQL用 存储过程做下面的内容

yujietim 发布于 2008-08-05 11:22, 837 次点击
有一表staff   如下:
id   managerid
1    null
2     1
3     2
4     1
5     4
6     2
7     6
8     1
9     1


当运行存储过程 得到一新表 结构如下
ID   Path
1    1
2    1,2
3    1,2,3
4    1,4
5    1,4,5
6    1,2,6
7    1,2,6,7
8    1,8
9    1,9



高手帮帮忙~!

[[it] 本帖最后由 yujietim 于 2008-8-5 16:07 编辑 [/it]]
3 回复
#2
yujietim2008-08-05 14:55
。。怎么没人额- - #
#3
bb38522008-08-06 09:45
-----建表
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
#4
bb38522008-08-06 09:46
-----测试,执行存储过程allid即可
1