MySQL存储过程,用变量定义CURSOR FOR

时间:2016-05-04 21:31:56

标签: mysql loops stored-procedures cursor

我在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)。

1 个答案:

答案 0 :(得分:0)

  1. 您应该在更新查询中使用current_animal而不是animal
 UPDATE farm_animal SET last_feed_time = now() WHERE id = current_animal;
  1. 离开的循环应为chores
 IF no_more_rows = TRUE THEN
        LEAVE chores;
    END IF;