mysql关于递归查询

通过编写一个存储过程来进行递归树状查询。

首先建立一个简单的员工表

drop table if exists business;
create table business(
id int primary key auto_creatment,
ssid int,
name varchar(8),
prefor float
);
通过最底层员工绩效查询公司所有人的绩效

创建存储过程,通过输入员工ID可以获取他的绩效;

在存储过程中判断如果绩效为空就获取其所有下属的ID,存储到游标中

通过获取游标值来获得下属绩效,如果下属绩效为空就继续调用自己。

drop procedure if exists performance;
delimiter //
create procedure performance(in c_id int,out num float)
BEGIN
-- 声明变量
declare a int default 0;
declare b double default 0;
declare pro float;
declare d_id int;
-- 声明用来终止游标的变量
declare done int default 0;
-- 声明游标cur
declare cur cursor for select id from business where ssid=c_id;
-- 当游标内没数据的时候将done赋值
declare continue handler for not found set done=1;

select produ into pro from business where id=c_id;
if pro<>0 then
set num=pro;
else

-- 打开游标
open cur;
read_loop:loop
fetch cur into d_id;
if done=1 then
leave read_loop;
end if;
select produ into pro from business where id=d_id;

if pro=0 then
call product(d_id,num);
set b=b+num;
set a=a+1;
else
set b = b+pro;
set a=a+1;
end if;

end loop;
close cur;
update bussniss set produ=(b/a) where id=c_id;
set num=(b/a);
end if; 

END
//
创建完成了,
在测试的过程出现了这种问题:ERROR 1456(HY0000):Recursive limit 0(as set by the max_sp_recursion_depth variable)
was exceeded for routine product
提示说设置的递归限度为0
这时设置一下SET max_sp_recursion_depth=15;就可以了,次数看情况定。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值