mysql 语句算法_求SQL语句递归的算法

表结构是这样的 部门 上级部门 A B B C C D A A B B C C 求一条SQL语句,根据A查其上级部门,查询结果为 上级部门 B C D ================================================= 用函数 create table tb (部门 varchar(20),上级部门 varchar(20)) insert into tb

表结构是这样的

部门 上级部门

A B

B C

C D

A A

B B

C C

求一条SQL语句,根据A查其上级部门,查询结果为

上级部门

B

C

D

=================================================

用函数

create table tb (部门 varchar(20),上级部门 varchar(20))

insert into tb select 'A','B' union all select 'B','C' union all select 'C','D'

union all select 'A','A' union all select 'B','B' union all select 'C','C'

--select * from tb

create function test_f (@name varchar(20))

returns @ta table(上级部门 varchar(20))

as

begin

--select @name=上级部门 from tb where 部门=@name and 部门!=上级部门

while exists(select 1 from tb where 部门=@name and 部门!=上级部门)

begin

insert @ta select 上级部门 from tb where 部门=@name and 部门!=上级部门

select @name=上级部门 from tb where 部门=@name and 部门!=上级部门

end

return

end

select * from dbo.test_f('A')

删除:

drop function test_f

drop table tb

上级部门

--------------------

B

C

D

(所影响的行数为 3 行)

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值