java sql 递归查询,SQL递归查询的几种实现方法

本文介绍了如何使用SQL的递归查询来获取产品类别层级结构,并展示了T-SQL代码示例。此外,还探讨了如何通过创建查询函数来查找特定ID下所有子部门及其成员,给出了具体的函数定义和测试数据,最后展示了查询结果。
摘要由CSDN通过智能技术生成

本节内容:

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 ParentCategoryID0--因为第一层前面已经查出来了,所以这里把第一层筛选掉

)

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

--调用函数进行查询

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   行)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值