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

Lana ·
更新时间:2024-05-16
· 1385 次阅读

目录

mysql存储过程游标loop循环

loop

mysql存储过程游标遍历使用简述

总结

mysql存储过程游标loop循环

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

loop DELIMITER $ 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_label loop_label: loop #将游标中的shopstoreid 这个值给到a FETCH c_cursor INTO a; # update执行的条件 IF b <4 THEN UPDATE shopstore SET storefansnum=74784 WHERE shopstoreid=b; SET b=b+1; END IF; IF b>=7 THEN LEAVE loop_label; END IF; #停止LOOP 循环 END LOOP loop_label; END $ CALL DAY081002()

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 总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



mysql存储过程 loop 游标 Mysql

需要 登录 后方可回复, 如果你还没有账号请 注册新账号