家族问题(难)

alipaymate 2005-03-25 11:16:18
表: family (parent_id char(10), child_id char(10))

现给出任一 parent_id.
怎么样才能得到 1. 这个parent下面的所有的child(子孙)总数?
2. 这个parent最大有几代(child)子孙?

如果一个parent 无 child , 则 child_id 的值为(null)空.

请高手帮忙!
...全文
61 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xluzhong 2005-03-25
  • 打赏
  • 举报
回复
http://blog.csdn.net/xluzhong/articles/326894.aspx
jinjazz 2005-03-25
  • 打赏
  • 举报
回复
--参考 好像是邹建写的
--示例

--测试数据
create table tb(父项 varchar(10),子项 varchar(10))
insert tb select 'a001','A1'
union all select 'a001','D1'
union all select 'a001','E1'
union all select 'A1' ,'B1'
union all select 'A1' ,'C1'
union all select 'E1' ,'C1'
union all select 'E1' ,'D1'
union all select 'E1' ,'F1'
go

--查询处理函数
create function f_id()
returns @re table(子项 varchar(10),[level] int,sid varchar(8000))
as
begin
declare @l int
set @l=1
insert @re select distinct 父项,@l,父项
from tb a
where not exists(select * from tb where 子项=a.父项)
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.子项,@l,b.sid+'>'+a.子项
from tb a,@re b
where a.父项=b.子项 and b.[level]=@l-1
end
return
end
go

--调用函数实现分级显示
select 层号=level,[部件号(产品号)]=子项
from f_id()
order by sid
go

--删除测试
drop table tb
drop function f_id

/*--结果

层号 部件号(产品号)
----------- ----------
1 a001
2 A1
3 B1
3 C1
2 D1
2 E1
3 C1
3 D1
3 F1

(所影响的行数为 9 行)
--*/

27,579

社区成员

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

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