MYSQL存储过程游标遍历使用简述
--游标样例:把users中的id为偶数的记录逐一更新用户名
create procedure test11
begin
declare stopflag int default 0 ;
declare username varchar(32) ;
--创建一个游标变量,declare变量名cursor...
declare username_cur cursor for select name from users where id%2=0;
--游标是保存查询结果的临时区域
--游标变量username_cur保存了查询的临时结果,实际上就是结果集
--当变量中保存的结果都查询一遍(遍历),到达结尾,将变量stopflag设置为1,用于循环中判断是否结束
declare continue handler for not found set stopflag = 1;
open username_cur ;--打开游标
fatch username_cur into username ;--游标向前走一步,取出一条记录放在变量 username 中
while (stopflag = 0) do --如果游标还没有结尾就继续
begin
--在用户名前拼接'_cur'字段
update users set name = concat(username,'_cur') where name = username ;
fetch username_cur into username;
end;
end while; --结束循环
close username_cur ; --关闭游标
end
--游标根据日期区间循环写入数据
create procedure f_rpt_g06
( in i_begin_date int ,
in i_end_date int )
begin
declare v_oc_date,v_m_begin_date int;
declare done int default 0;
-- 游标循环处理输出入参数日期区间的数据
declare cur cursor for
select oc_date from dim_date
where oc_date between i_begin_date and i_end_date
order by oc_date asc;
--将变量done设置为1,用于循环中判断是否交结束
declare continue hadnler for not found set done = 1;
--打开游标
open cur;
dateloop:loop
--游标向前走一步,取出一条记录放在变量v_oc_date中
fetch cur into v_oc_date;
if done=1 then
leave dateloop;
end if;
--删除表数据
delete from f_rpt_g06
where data_dt = v_oc_date
--插入表数据
insert into f_rpt_g06
(字段1,字段2,字段3,字段4)
select 字段1,字段2,字段3,字段4 from f_rpt_g06_123
end loop dateloop
close loop
end