我在 MySQL 中的存储过程也遇到了同样的问题。它应该从一个表中获取某个列中具有空值的所有记录,然后从另一个表中填充该值。然而,它在一个记录后停止了:
CREATE PROCEDURE `updateRecord`()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE recordId, newValue INT;
DECLARE current_record CURSOR FOR SELECT id FROM A where b_id is null;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN current_record;
main_loop: LOOP
FETCH current_record INTO recordId;
IF done THEN
LEAVE main_loop;
END IF;
-- fetching some value from table b
select id into newValue from B where ...
-- setting new value in record
update A set b_id = newValue where id = recordId;
END LOOP;
END
答案是“未找到的处理程序”不仅在游标未返回任何行时执行,而且在表 B 上的选择未返回任何行时执行。我的解决方案是使用由处理程序设置的第二个变量,并在选择后重置“完成”变量:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE, noBfound = TRUE;
[...]
select id into newValue from B where ...
IF (noBfound = TRUE) THEN
SET done = FALSE;
END IF;
[...]
加法:显然可以通过在选择后简单地重置“完成”来不使用第二个变量:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
[...]
select id into newValue from B where ...
SET done = FALSE;
[...]