我在MySQL中创建一个存储过程来循环遍历一组值,并对每个值执行相同的INSERT / UPDATE操作。
INSERT / UPDATE操作保持不变,但是在我编写的脚本中,需要循环的值会发生变化。以下是我尝试做的简化示例:
DELIMITER $$
CREATE PROCEDURE `log_feed_times`()
BEGIN
DECLARE `no_more_rows` BOOLEAN;
DECLARE `current_animal` INT DEFAULT 0;
DECLARE `animal` CURSOR FOR @query;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
OPEN `animal`;
chores: LOOP
FETCH `animal` INTO `current_animal`;
IF no_more_rows = TRUE THEN
LEAVE move_now;
END IF;
UPDATE farm_animal SET last_feed_time = now() WHERE id = `animal`;
END LOOP chores;
CLOSE `animal`;
END$$
DELIMITER ;
SET @query = "SELECT id FROM farm_animal WHERE name IN ('horse', cow')";
CALL `log_feed_times`;
SET @query = "SELECT id FROM farm_animal WHERE name IN ('pig', 'duck')";
CALL `log_feed_times`;
到目前为止,我尝试这样做导致ERROR 1064(42000)。
答案 0 :(得分:0)
current_animal
而不是animal
。 UPDATE farm_animal SET last_feed_time = now() WHERE id = current_animal;
chores
IF no_more_rows = TRUE THEN
LEAVE chores;
END IF;