将游标变量提取到局部变量中

时间:2016-11-17 10:59:41

标签: mysql sql cursor prepared-statement

是否可以将游标变量提取到局部变量中?这样我就可以将它们用于准备好的声明中。

    DROP PROCEDURE IF EXISTS `01_input_brut`.test_cursor;
CREATE DEFINER=`root`@`%` PROCEDURE `test_cursor`()
BLOCK1: BEGIN
    DECLARE no_more_rows1 INT;
    DECLARE my_name VARCHAR(255);
    DECLARE civility VARCHAR(255);

    DECLARE curseur1 CURSOR FOR
        SELECT `name`
        FROM source;

    DECLARE CONTINUE handler FOR NOT FOUND SET no_more_rows1 = TRUE;

    OPEN curseur1;

    LOOP1: LOOP
                set no_more_rows1 = false;
        FETCH curseur1 INTO @my_name;
        IF no_more_rows1 THEN
            CLOSE curseur1;
            LEAVE LOOP1;
        END IF;

INSERT INTO log (id, message, date) VALUES (NULL, @my_name, NOW());


    END LOOP LOOP1;     
END BLOCK1;

这只是给我一个SQL语法错误。

编辑1

这是一个程序例子,除非我删除" @"来自" FETCH curseur1 INTO @my_name;" :

{{1}}

错误:

  

[2016-11-17 16:19:34] [42000] [1064]您的SQL中有错误   句法;查看与MySQL服务器版本对应的手册   正确的语法使用在' @my_name附近;           如果no_more_rows1那么               关闭curseur1;               '在第17行

1 个答案:

答案 0 :(得分:0)

尝试:

DROP TABLE IF EXISTS `source`;
DROP TABLE IF EXISTS `log`;
DROP PROCEDURE IF EXISTS `test_cursor`;

CREATE TABLE IF NOT EXISTS `source` (
  `name` VARCHAR(255)
);

CREATE TABLE IF NOT EXISTS `log` (
  `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `message` VARCHAR(255),
  `date` DATETIME
);

INSERT INTO `source` (`name`)
VALUES ('name 1');

DELIMITER //

CREATE PROCEDURE `test_cursor`()
`BLOCK1`: BEGIN
  -- DECLARE `no_more_rows1` INT;
  DECLARE `no_more_rows1` BOOL DEFAULT FALSE;
  DECLARE `my_name` VARCHAR(255);
  -- DECLARE `civility` VARCHAR(255);

  DECLARE `curseur1` CURSOR FOR
    SELECT `name`
    FROM `source`;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET `no_more_rows1` := TRUE;

  OPEN `curseur1`;

  `LOOP1`: LOOP
    -- set no_more_rows1 = false;
    -- FETCH curseur1 INTO @my_name; <- User-Defined Variable. See http://dev.mysql.com/doc/refman/5.7/en/user-variables.html
    FETCH `curseur1` INTO `my_name`;
    IF `no_more_rows1` THEN
      CLOSE `curseur1`;
      LEAVE `LOOP1`;
    END IF;

    INSERT INTO `log` (`id`, `message`, `date`)
    -- VALUES (NULL, @my_name, NOW());
    VALUES (NULL, `my_name`, NOW());
  END LOOP `LOOP1`;
END `BLOCK1`//

DELIMITER ;

CALL `test_cursor`;

SELECT `name`
FROM `source`;

SELECT `id`, `message`, `date`
FROM `log`;

请参阅SQL Fiddle demo