MySQL 存储过程,获取使用游标查询的结果集
MySQL 存储过程中,使用游标查询,返回的是结果集时,如何查看调用存储过程输出结果呢?
解决方案:存储过程不返回数据,但它能创建和填充另一个表。所以在存储过程运行中创建临时表。该临时表将保存存储过程中生成的结果集,在遍历游标时,用insert保存每条数据到临时表中。后续调用时可以用select语句查询临时表中的存储过程运行结果。
以下有 三种方式 使用游标创建一个存储过程,统计某一部门下的员工信息
方法一:Loop循环
DROP PROCEDURE IF EXISTS pro_empIndepart_list;
delimiter //
CREATE PROCEDURE pro_empIndepart_list (IN departid INT)
BEGIN
-- 创建 用于接收游标值的变量
DECLARE c_id,c_salary INT;
-- 注意 接收游标值为中文时 需要 给变量 指定 字符集为utf8
DECLARE c_empname,c_job VARCHAR(50) character set utf8;
-- 游标结束的标志
DECLARE done INT DEFAULT 0;
DECLARE cur CURSOR for select e.id,e.yuangongname,e.word,e.wage from emp e where e.bumenTableId=departid;
DECLARE continue handler for not found set done = 1;
create table if not exists emp_dempart_temp1(id int,empname VARCHAR(50),job VARCHAR(50),salary int);
OPEN cur;
emplist:LOOP
FETCH cur INTO c_id,c_empname,c_job,c_salary;
if done = 1 THEN
leave emplist;
end if;
insert into emp_dempart_temp1(id,empname,job,salary) values(c_id,c_empname,c_job,c_salary);
end LOOP;
CLOSE cur;
END //
delimiter ;
调用存储过程:
CALL pro_empIndepart_list(4);
select * from emp_dempart_temp1;
DELETE from emp_dempart_temp1;
DECLARE done boolean default 0;
DECLARE c_id,c_salary INT;
-- 注意 接收游标值为中文时 需要 给变量 指定 字符集为utf8
DECLARE c_empname,c_job VARCHAR(50) character set utf8;
DECLARE cur cursor for
select e.id,e.yuangongname,e.word,e.wage from emp e where e.bumenTableId=departid;
DECLARE continue handler for sqlstate '02000' set done=1;
create table if not exists emp_dempart_temp2(id int,empname VARCHAR(50),job VARCHAR(50),salary int);
truncate TABLE emp_dempart_temp2;
open cur;
WHILE done !=1 DO
fetch cur into c_id,c_empname,c_job,c_salary;
if done != 1 then
insert into emp_dempart_temp2(id,empname,job,salary) values(c_id,c_empname,c_job,c_salary);
end if;
END WHILE;
close cur;
end//
delimiter;
调用存储过程:
CALL empIndepart_list2(4);
select * from emp_dempart_temp2;
DELETE from emp_dempart_temp2;
DECLARE done boolean default 0;
DECLARE c_id,c_salary INT;
-- 注意 接收游标值为中文时 需要 给变量 指定 字符集为utf8
DECLARE c_empname,c_job VARCHAR(50) character set utf8;
DECLARE cur cursor for
select e.id,e.yuangongname,e.word,e.wage from emp e where e.bumenTableId=departid;
DECLARE continue handler for sqlstate '02000' set done=1;
create table if not exists emp_dempart_temp(id int,empname VARCHAR(50),job VARCHAR(50),salary int);
truncate TABLE emp_dempart_temp;
open cur;
REPEAT
fetch cur into c_id,c_empname,c_job,c_salary;
if done != 1 then
insert into emp_dempart_temp(id,empname,job,salary) values(c_id,c_empname,c_job,c_salary);
end if;
until done =1 end repeat;
close cur;
end//
delimiter;
调用存储过程:
CALL empIndepart_list(2);
select * from emp_dempart_temp;
DELETE from emp_dempart_temp;