mysql关于递归查询

来源:互联网 发布:学安卓好还是java好 编辑:程序博客网 时间:2024/05/17 02:09

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

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

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;
-- 声明游标curdeclare 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 thenset num=pro;else
-- 打开游标
open cur;read_loop:loopfetch cur into d_id;if done=1 thenleave read_loop;end if;select produ into pro from business where id=d_id;if pro=0 thencall product(d_id,num);set b=b+num;set a=a+1;elseset 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