一个递归查询的问题

redfoxhuang 2003-10-15 11:35:56
两个表a,b
a表是树形的结构,两个字段id,pid(父记录id)
例如
id pid
0,0
1,0
2,0
3,1
b表是具体的信息,有一个a_id的字段保存a表对应的id
我想将程序中的递归移到数据端进行,就是将a表中id为0的相对应的数据和子都取出来,不知道怎样写
...全文
27 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
redfoxhuang 2003-10-15
  • 打赏
  • 举报
回复
zjcxc(邹建)
我看过你那篇树的文章,用你的给的例子和数据可以实现,
可是我自己试着用到自己的数据和表就不行了,只出来了一层子节点
能不能解释一下例子中那一段代码实现了递归?
就是我用语言的递归就是
function aa()
{
aa()
}
那数据库的递归的原理是什么呢?
zjcxc 元老 2003-10-15
  • 打赏
  • 举报
回复
调用上面的函数实现你的查询:

select * from dbo.getchildid(0) a inner join b on a.id=b.a_id
zjcxc 元老 2003-10-15
  • 打赏
  • 举报
回复
/*-- 得到指定id的子id列表 --*/
--不包含排序字段的情况
create function f_getchildid(@id int)
returns @re table(id int)
as
begin
insert into @re select id from tb where pid=@id
while @@rowcount>0
insert into @re select a.id
from aa inner join @re b on a.pid=b.id
where a.id not in(select id from @re)
return
end
go

CrazyFor 2003-10-15
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/1375/1375432.xml?temp=.8570978
pengdali 2003-10-15
  • 打赏
  • 举报
回复
举例:

declare @a table (TC_Id int,TC_PID int,TC_Name varchar(200))
insert @a values(1,0,'中国')
insert @a values(2,0,'美国')
insert @a values(3,0,'加拿大')
insert @a values(4,1,'北京')
insert @a values(5,1,'上海')
insert @a values(6,1,'江苏')
insert @a values(7,6,'苏州')
insert @a values(8,7,'常熟')
insert @a values(9,6,'南京')
insert @a values(10,6,'无锡')
insert @a values(11,2,'纽约')
insert @a values(12,2,'旧金山')

declare @tmp1 table (TC_Id int,TC_PID int,TC_Name varchar(200),lev int)
insert @tmp1 select *,1 from @a where tc_ID=1
while exists(select 1 from @a a,@tmp1 b where a.tc_pid=b.tc_ID and a.tc_ID not in (select tc_ID from @tmp1))
insert @tmp1 select a.*,1 from @a a,@tmp1 b where a.tc_pid=b.tc_ID and a.tc_ID not in (select tc_ID from @tmp1)
select * from @tmp1
txlicenhe 2003-10-15
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/2285/2285830.xml?temp=.1570551

/*--树形数据处理方案

树形数据的排序,新增,修改,复制,删除,数据完整性检查,汇总统计
--邹建 2003.9--*/

34,575

社区成员

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

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