请问这如何解决呢

kiki12 2004-11-06 04:37:24
有一个简单的表(id,parent_id,name),其中Id是主键,parent_id是父ID,现在有这样一个需求,统计一个parent_id的所有下级名字,如(parent_id,name1+','+ name2 + ...)这样的形式,
我发现难度很大,光用SQL似乎很难实现。
如果用存储过程,需要用到两个游标,第一个放parent_id,而第二个是一个内部游标,根据第一个游标的值查询出每个子记录,然后取出每个内部游标进行处理。我不想写内部游标,请问大侠们有好的解决方案。
...全文
43 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
mgsray 2004-11-06
  • 打赏
  • 举报
回复
--参考
select * from tb
create table tb(id int identity(1,1),pid int,name varchar(20))
insert tb select 0,'中国'
union all select 0,'美国'
union all select 0,'加拿大'
union all select 1,'北京'
union all select 1,'上海'
union all select 1,'江苏'
union all select 6,'苏州'
union all select 7,'常熟'
union all select 6,'南京'
union all select 6,'无锡'
union all select 2,'纽约'
union all select 2,'旧金山'
go

--查询指定id的所有子
create function f_cid(
@id int
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from tb a,@re b
where a.pid=b.id and b.level=@l-1
end
/*--如果只显示最明细的子(下面没有子),则加上这个删除
delete a from @re a
where exists(
select 1 from tb where pid=a.id)
--*/
return
end
go

--调用(查询所有的子)
select a.*,层次=b.level from tb a,f_cid(2)b where a.id=b.id
go

--查询指定id的所有父
create function f_pid(
@id int
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select pid,@l from tb where id=@id and pid<>0
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.pid,@l
from tb a,@re b
where a.id=b.id and b.level=@l-1 and a.pid<>0
end
return
end
go

--调用(查询所有的父)
select a.* from tb a,f_pid(7)b where a.id=b.id
go

--删除测试
drop table tb
drop function f_cid
drop function f_pid

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧