在尝试嵌套游标时获取MySQL存储过程中的语法错误

时间:2017-10-26 15:13:03

标签: mysql sql stored-procedures

我有一个MySQL存储过程脚本,我试图在其中实现嵌套游标。以下是我的代码

DELIMITER //
DROP PROCEDURE IF EXISTS PopulateStaleEntityTable//
DELETE FROM bucket_stale;
LOAD DATA LOCAL INFILE '/home/centos/mysql1.txt' INTO TABLE bucket_stale;
CREATE PROCEDURE PopulateStaleEntityTable()
   BEGIN
    DECLARE finished INTEGER DEFAULT 0;
        DECLARE finished_stale INTEGER DEFAULT 0;
    DECLARE product_offer_id_var bigint(20) DEFAULT 0;
    DECLARE product_offer_group_id_var bigint(20) DEFAULT 0;
    DECLARE batch_count INTEGER DEFAULT 0;
        DECLARE max_batch_count INTEGER DEFAULT 100;
        DECLARE bucket_id_var bigint(10) DEFAULT 0;
        DECLARE stale_cursor CURSOR FOR 
        SELECT staleid FROM bucket_stale;
        DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET finished_stale = 1;
        OPEN stale_cursor;
        insert_stale : LOOP
        FETCH stale_cursor INTO bucket_id_var;
    SELECT bucket_id_var; 
    BEGIN
    DECLARE product_cursor CURSOR FOR 
        SELECT product_offer_id FROM product where bucket_id='1086';
        DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET finished = 1;
    OPEN product_cursor;
        insert_entity: LOOP
        START TRANSACTION;
        FETCH product_cursor INTO product_offer_id_var;
        SELECT product_offer_group_id INTO product_offer_group_id_var FROM product_offer where id=product_offer_id_var;
        INSERT IGNORE INTO stale_cached_entity (entity_type,entity_id,cache_action,created,field_change) VALUES          ('PRODUCT_OFFER_GROUP',product_offer_group_id_var,  'UPDATE',now(),'DEFAULT_SUPC_LIST1'); 
            SET batch_count=batch_count+1;
            IF batch_count > max_batch_count THEN 
            COMMIT;
            SET batch_count=0;
        END IF;
        IF finished = 1 THEN 
        LEAVE insert_entity;
    END IF;
    END LOOP insert_entity
    END;
        IF finished_stale = 1 THEN 
        LEAVE insert_stale;
        END IF;   
    END LOOP insert_stale;
        CLOSE stale_cursor;
   END//
DELIMITER ;

当我尝试运行此脚本时,它会出现以下错误

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 'END;
        IF finished_stale = 1 THEN 
   LEAVE insert_stale;
        END IF; ' at line 38

我试图弄清楚什么是错的,但我不能。我错过了什么?

1 个答案:

答案 0 :(得分:1)

问题出在这一行:

END LOOP insert_entity

如果查看https://dev.mysql.com/doc/refman/5.7/en/cursors.html处的游标代码示例,您会发现END LOOP不需要该标签,并且它需要一个分号语句终止符。

像这样:

END LOOP;

我同意@ tadman的评论。我理解一些有Oracle或Microsoft经验的开发人员期望使用存储过程,但坦率地说,MySQL的存储过程支持非常糟糕,编写一些简单的Python脚本(或其他任何其他内容)会更快乐,更有效率式语言)。

相关问题