背景:有多张表,每张表里存在一个相同的字段,为表一的id。此id可通过表一另一字段查询得到,另一字段为外部输入。现在别人写一存储过程,外部输入所需条件字段,删除每张表内设计到的数据。
先上代码:
BEGIN
declare userPramId VARCHAR(50); -- 声明变量
declare p_i int default 0;
declare p_i_limit int default 1; -- 一次执行,删除上限
declare p_finished int default 0; -- 遍历结束标志
declare iterator_user cursor for -- 声明游标
select id from 表一 where sexId = sexPramId;
declare iterator_log cursor for
select * from log_delete_user_in;
declare continue handler for NOT FOUND set p_finished = 1; -- 遍历结束捕获
-- create tmp log table
drop table if exists log_delete_user_in;
create table log_delete_user_in
(
userId varchar(50)
);
open iterator_user; -- 打开游标
fetch iterator_user into userPramId; -- fetch循环遍历
repeat -- 遍历
DELETE FROM 表二 WHERE id in (SELECT patient_id FROM 表一 WHERE id = userPramId);
delete from 表三 where userId = userPramId;
delete from 表四 where userId = userPramId;
delete from 表五 where userId = userPramId;
delete from 表六 where userId = userPramId;
set p_i = p_i + 1;
insert into log_delete_user_in select userPramId; -- log
fetch iterator_user into userPramId; -- 新赋值进行下一次循环
until p_finished end repeat;
-- until p_finished || p_i >= p_i_limit end repeat;
close iterator_user; -- 关闭游标
-- delete 表一
set p_finished = 0;
open iterator_log;
fetch iterator_log into userPramId; -- fetch循环游标并赋值
repeat -- 遍历执行
delete from 表一 where id = userPramId;
fetch iterator_log into userPramId;
until p_finished end repeat;
close iterator_log;
select CONCAT('delete_hospital_history_in ',p_i,',sexId ',sexId);
END
代码中注释乃自己加的,不对的地方忘指正。希望大佬指教。
不明白之处:
1.p_finished:此声明的字段是怎么起到作用的?
2.declare continue handler for NOT FOUND set p_finished = 1; – 遍历结束捕获 ,这里的作用和意义目前不明确。