如何在SQL中递归查询数据?

asthlon 2004-06-21 10:38:27
ID 是否为部门 部门名 上级ID
1 y 部门0 1
31 y 部门1 1
32 n 张三 31
33 n 李二 31
34 y 部门2 31
35 n 王五 34
35 y 部门3 34
36 n 小三 35
我想找询 ID 值为 35 下级的所有人员包括下级部门的所有人员
请各位指教,谢谢
...全文
1073 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
MitnickChen 2004-07-02
  • 打赏
  • 举报
回复
好方法!
zjcxc 2004-06-21
  • 打赏
  • 举报
回复
--对函数及调用的一些说明.

--创建查询函数
create function f_id(
@id int --要查询的id
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select id,@l
from 表
where 上级id=@id --如果要包含查询的id,改条件为:id=@id
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from 表 a join @re b on a.上级id=b.id and b.level=@l-1
end
return
end
go

--调用函数进行查询
select a.* from 表 a join f_id(35) b on a.id=b.id
--where a.是否为部门='n' --如果只显示人员,加上条件
zjcxc 2004-06-21
  • 打赏
  • 举报
回复
--测试

--测试数据
create table 表(ID int,是否为部门 char(1),部门名 varchar(10),上级ID int)
insert 表 select 1 ,'y','部门0' ,1
union all select 31,'y','部门1' ,1
union all select 32,'n','张三' ,31
union all select 33,'n','李二' ,31
union all select 34,'y','部门2',31
union all select 35,'n','王五' ,34
union all select 35,'y','部门3',34
union all select 36,'n','小三' ,35
go

--创建查询函数
create function f_id(
@id int --要查询的id
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select id,@l
from 表
where 上级id=@id
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from 表 a join @re b on a.上级id=b.id and b.level=@l-1
end
return
end
go

--调用函数进行查询
select a.* from 表 a join f_id(35) b on a.id=b.id
go

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

/*--测试结果

ID 是否为部门 部门名 上级ID
----------- ----- ---------- -----------
36 n 小三 35

(所影响的行数为 1 行)
--*/
zjcxc 2004-06-21
  • 打赏
  • 举报
回复
--创建查询函数
create function f_id(
@id int --要查询的id
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select id,@l
from 表
where 上级id=@id
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.id,@l
from 表 a join @re b on a.上级id=b.id and b.level=@l-1
end
return
end
go

--调用函数进行查询
select a.* from 表 a join f_id(35) b on a.id=b.id
asthlon 2004-06-21
  • 打赏
  • 举报
回复
ID 为主键
asthlon 2004-06-21
  • 打赏
  • 举报
回复
我想找询 ID 值应该为 31 下级的所有人员包括下级部门的所有人员
victorycyz 2004-06-21
  • 打赏
  • 举报
回复

ID值可重复的吗?

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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