敬请版主,大哥,大侠们帮帮忙?在线等待!谢谢谢谢谢谢!

我有一个BBS。有一个id,和fatherid.
其中fatherid保存的是bbs的父接点 。
比如: id 1 title "ggg" fatherid 0
当fatherid为0时表示是发表的论坛。

id 2 title "dfafad" fatherid 1
id 3 title "asdfas" fatherid 1
id 4 title "asdf" fatherid 2
id 5 title "asdfsf" fatherid 2
..........

这样就表示是id 号为1的回复的帖子 。
现在我要把所有fatherid=0且他的回复的数用字段counts显示出来
就是 : id 1 title "ggg" fatherid 0 counts 4
(只要是他的下级的都统计出来,是不是要用到递归???)

---------------------------------------------------------------

create function GetCount(@id int)
returns int
as
begin
declare @tmp table (id int)
declare @c int
insert @tmp select id from yourtablename where fatherid=@id
while exists (
select id from yourtablename where fatherid in (select id from @tmp) and id not in (select id from @tmp)
)
insert @tmp select id from yourtablename where fatherid in (select id from @tmp) and id not in (select id from @tmp)

select @c=count(*) from @tmp
return @c
end

调用:
select *,dbo.GetCount(id) as Counts from yourtablename
where fatherid=0

没有测试!
---------------------------------------------------------------

不一定要用递归,

曾经做过一个类似的,说一下我的思路吧。
一个循环,
只要第次循环过后,发现数量有变化,就说明还可能有数量没有统计进去,否则就是所要的count数。

---------------------------------------------------------------

GZ

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus