视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
SQL数据库实现递归查询的几种代码方法
2020-11-09 16:15:46 责编:小采
文档


SQL数据库实现递归查询的几种代码方法 表结构 ProductCategory CategoryID,Level,ParentCategoryID 数据 1,1,-1 2,1,-1 3,2,1 4,3,3 5,2,2 6,4,5 T-SQL WITH CategoryTemp(CategoryID,ParentCategoryID)--临时表用来保存查到的Category ( SELECT CategoryI

SQL数据库实现递归查询的几种代码方法
表结构

ProductCategory

CategoryID,Level,ParentCategoryID

数据

1,1,-1

2,1,-1

3,2,1

4,3,3

5,2,2

6,4,5

T-SQL

WITH CategoryTemp(CategoryID,ParentCategoryID)--临时表用来保存查到的Category

(

  SELECT CategoryID,ParentCategoryID FROM ProductCategory WHERE ParentCategoryID<=0--将所有的第一层查出来作为初始数据,需要查第几层或者哪个ParentCategoryID下面所有的 N层,把ParentCategoryID赋相关的值即可

  UNION ALL--查询N层

  SELECT pc.CategoryID,ParentCategoryID FROM ProductCategory pc

  LEFT JOIN CategoryTemp ct ON pc.ParentCategoryID=ct.CategoryID

  WHERE ParentCategoryID>0--因为第一层前面已经查出来了,所以这里把第一层筛选掉

)

SELECT CategoryID,ParentCategoryID FROM CategoryTemp

结果

1,-1

2,-1

3,1

4,3

5,2

6,5

如果把ParentCategoryID赋为2,结果则为

5,2

6,5

实例

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 下级的所有人员包括下级部门的所有人员

--创建查询函数
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

联合查询

--测试数据
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

下载本文
显示全文
专题