游标循环中的MySQL语法错误

时间:2017-12-06 17:13:13

标签: mysql loops stored-procedures cursor syntax-error

我正在尝试使用此脚本在存储过程中运行游标循环:

CREATE PROCEDURE migrateMStruct()
BEGIN
DECLARE finished INT DEFAULT FALSE;
DECLARE msId BIGINT(20) UNSIGNED;
DECLARE luId INT(11);

DECLARE msCursor CURSOR FOR
    SELECT id, live_unit_id FROM mounting_structures
    WHERE live_unit_id IS NOT NULL;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = TRUE;

OPEN msCursor;

read_loop: LOOP
    FETCH msCursor INTO msId, luId;
    IF finished THEN
        LEAVE read_loop;
    END IF;
    UPDATE live_units SET mountingStructureId = msId WHERE live_units.id = luId;
END LOOP;

CLOSE msCursor;
END;

我根据MySQL文档编写了这个脚本,但是在执行脚本时我收到了错误:

SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual 
that corresponds to your MySQL server version for the right syntax to use near '' 
at line 19

第19行只是END IF;语句。显然不是世界上最有用的错误,但基于MySQL的文档,语法看起来是正确的。

1 个答案:

答案 0 :(得分:1)

我得到了同样的错误,你必须更改分隔符字符临时以防止在SQL解释器找到分号;

时执行
DELIMITER $$ 

CREATE PROCEDURE migrateMStruct()
BEGIN

  /*your procedure body*/

END$$

DELIMITER ;  /*back to previous delimiter*