求SQL语句(递归查询) --------分不够可再加

foreverghost 2004-07-22 11:04:45
有一张表,info其中有两个字段,ID(本身ID),UPID(上一级ID)
ID UPID ..................
1
2 1
3 1 如: 1
4 2 |___2___4
5 1 | |___7
6 3 |___3___6
7 2 |___5

我现在要求ID为1的这个节点下共有多小个子节点,直接子节点和间接子节点都算,所以返回的数字应该是6,不知道能不能用SQL语句求出,请大侠们帮帮忙,小弟急用。

...全文
271 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
popmailzjw 2004-07-22
  • 打赏
  • 举报
回复
study
loverpyh 2004-07-22
  • 打赏
  • 举报
回复
up
tx1icenhe 2004-07-22
  • 打赏
  • 举报
回复
--建立测试表
create table info (
ID int ,
UPID int
)
go

--插入数据
insert info
select
1,null
union all select
2, 1
union all select
3, 1
union all select
4, 2
union all select
5, 1
union all select
6, 3
union all select
7, 2

go

--建立函数
CREATE function fn_Num(@Id int)
returns int
as
begin
declare @r int
set @r=0
if not exists (select 1 from info where Id=@id)
return @r
if not exists (select 1 from info where UpId=@id)
return @r
declare @t table (Id int)

insert @t(Id) select id from info where Upid=@id

while exists (select Id from info where UpId in (select Id from @t)
and Id not in (select Id from @t)
)
insert @t(Id)
select Id from info where UpId in (select Id from @t)
and Id not in (select Id from @t)

select @r=count(distinct Id) from @t
return @r
end



GO

--调用测试
select dbo.fn_Num(1)

--结果
/*

-----------
6

(所影响的行数为 1 行)

*/
foreverghost 2004-07-22
  • 打赏
  • 举报
回复
知道了,谢谢,你已经给我解决很大问题,小弟不胜感激。
tx1icenhe 2004-07-22
  • 打赏
  • 举报
回复
可以这么查询:
select *,dbo.fn_Num(id) as cnt
from info

/*
结果:
ID UPID cnt
----------- ----------- -----------
1 NULL 6
2 1 2
3 1 1
4 2 0
5 1 0
6 3 0
7 2 0

(所影响的行数为 7 行)

*/
tx1icenhe 2004-07-22
  • 打赏
  • 举报
回复
问题是,你说的树有可能有十几层,这个程序已经解决

应该可以查询任意一个节点下的子节点的个,这个程序也已经解决,只要你变换参数就可以

tx1icenhe 2004-07-22
  • 打赏
  • 举报
回复
喂,不是分的问题
foreverghost 2004-07-22
  • 打赏
  • 举报
回复
不好意思,我是初学者,我已经测试过了,谢谢你,马上给分。。。
tx1icenhe 2004-07-22
  • 打赏
  • 举报
回复
啊?

楼主这么说我就不想说什么了,我肯定的说,你并没有明白这段程序,也没有测试

csdn这样的事情太多,实在是没话好说
foreverghost 2004-07-22
  • 打赏
  • 举报
回复
对了,再补充一点。查询时,应该可以查询任意一个节点下的子节点的个。
foreverghost 2004-07-22
  • 打赏
  • 举报
回复
to:tx1icenhe(冒牌马可 V0.1)
  你的方法很好,但我用不上,因为我的这个树有可能有十几层,也就是说4下面可能有,7下面也可以有,一直延续到很多层,所以我用不上,不过还是谢谢你。

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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