您的位置:首页技术文章
文章详情页

mysql存储过程游标之loop循环解读

【字号: 日期:2023-07-05 19:48:16浏览:5作者:猪猪
目录mysql存储过程游标loop循环loopmysql存储过程游标遍历使用简述总结mysql存储过程游标loop循环

mysql存储过程游标 一共有3中循环方式 while, repeat, loop,

loopDELIMITER $CREATE PROCEDURE DAY081002()BEGIN#定义参数 后面使用DECLARE a INT;DECLARE b INT DEFAULT 0;# 定义游标DECLARE c_cursor CURSOR FOR SELECT shopstoreid FROM shopstore;OPEN c_cursor; #开启游标#定义loop循环 循环名字为 loop_labelloop_label: loop#将游标中的shopstoreid 这个值给到aFETCH c_cursor INTO a;# update执行的条件IF b <4 THENUPDATE shopstore SET storefansnum=74784 WHERE shopstoreid=b;SET b=b+1;END IF;IF b>=7 THENLEAVE loop_label;END IF;#停止LOOP 循环END LOOP loop_label;END $CALL DAY081002()

mysql存储过程游标遍历使用简述--游标样例:把users中的id为偶数的记录逐一更新用户名create procedure test11begin 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_datewhere oc_date between i_begin_date and i_end_dateorder 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 thenleave dateloop;end if;--删除表数据delete from f_rpt_g06where data_dt = v_oc_date--插入表数据insert into f_rpt_g06(字段1,字段2,字段3,字段4)select 字段1,字段2,字段3,字段4 from f_rpt_g06_123end loop dateloopclose loopend 总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: MySQL 数据库
相关文章: