【问题标题】:SQL Cursor syntax errorSQL 游标语法错误
【发布时间】:2016-12-22 12:05:22
【问题描述】:

我一直在为这个问题头疼。在 SO 上找不到任何答案,所以如果有人能帮助我,我会很感激!

以下查询导致 suntax 错误。有什么线索吗?

BEGIN
    DECLARE cur CURSOR FOR
    SELECT * FROM objects
    WHERE present_in_last_scrape = FALSE;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    OPEN cur;
        DECLARE done INT DEFAULT 0; 
        read_loop: LOOP
            FETCH cur INTO record;
            IF done THEN
                LEAVE read_loop;
            END IF;
            UPDATE lifetimes SET end_time=extract(epoch from now()) WHERE object_id=record.object_id AND end_time IS NULL;
        END LOOP;
    CLOSE cur;
END

语法错误:

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 'DECLARE cur CURSOR FOR
    SELECT * FROM objects
    WHERE present_in_last_scrap' at line 2
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 'DECLARE cur CURSOR FOR
    SELECT * FROM objects
    WHERE present_in_last_scrap' at line 2
  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 'DECLARE cur CURSOR FOR
    SELECT * FROM objects
    WHERE present_in_last_scrap' at line 2
  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 'DECLARE cur CURSOR FOR
    SELECT * FROM objects
    WHERE present_in_last_scrap' at line 2

【问题讨论】:

  • Cursor declarations must appear before handler declarations and after variable and condition declarations.。见14.6.6.2 Cursor DECLARE Syntax
  • 听起来@wchiquito 有您的解决方案,但如果没有,发布您遇到的确切错误可能会对您有所帮助。
  • @wchiquito 不是这样吗?
  • 不应该 DECLARE done INT DEFAULT 0;在游标声明之前。
  • 你需要声明一个名为record的变量,什么是extract(epoch from now())?

标签: mysql cursor


【解决方案1】:

感谢大家的帮助!时代的东西确实是postgresql,已经改变了。 @solarflare 的 create_procedure 评论是正确的,最终成功了!

CREATE PROCEDURE set_end_time (out done int)
BEGIN   
    DECLARE cur CURSOR FOR
        SELECT * FROM objects
        WHERE present_in_last_scrape = FALSE;

    OPEN cur;       
        LOOP
            UPDATE lifetimes SET end_time=UNIX_TIMESTAMP(NOW()) WHERE hemnet_id=cur.hemnet_id AND end_time IS NULL;
        END LOOP;
    CLOSE cur;
END

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多