最近又用需要用到游标,做个笔记,直接上代码了
-- 创建存储过程
delimiter //
create procedure company_attachment_cursor(in _type int)
begin
-- 申明局部变量 declare
declare _company_id varchar(25);
declare targetId varchar(25);
declare num int;
DECLARE done int DEFAULT FALSE;
-- 申明游标
declare cur1 CURSOR FOR select distinct company_id from company_attachment where type=_type;
-- 第二个游标需使用第一个循环的变量_company_id,故将变量申明在最外层
declare cur2 CURSOR FOR select id from company_attachment where company_id=_company_id and type=_type;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
open cur1;
read_loop: LOOP
fetch cur1 into _company_id;
IF done THEN
LEAVE read_loop;
END IF;
-- 每次循环开始时重新对num进行赋值
set num = 0;
-- 开启第二个游标
open cur2;
inner_loop: LOOP
fetch cur2 into targetId;
-- 打印过程
-- select num;
IF done THEN
LEAVE inner_loop;
END IF;
update company_attachment set number=num where id=targetId;
set num=num+1;
END LOOP;
close cur2;
-- 第一个循环结束时done=1
-- 故需手动设置done=0,否则外层循环仅会执行一次
SET done = 0;
END LOOP;
close cur1;
end; //
语法上的几个容易错误的地方。
- 在LOOP中使用declare申明,应当将declare全部申明在最外层
- HANDLER 只能申明一个
- 当内循环结束之后,应当将done设为0,以防止外层循环进入时直接会结束循环。
欢迎关注我的个人公众号:逍遥的心。主推程序员写的生活类文章,有兴趣的朋友可以共同探讨下: