如何在游标中使用NEW值(在插入触发器Mysql之后)

时间:2016-06-30 11:47:57

标签: mysql triggers cursor

插入trigger后我有一个表使用。我想用游标来循环perpose logic.I试试这个简单的声明游标

DECLARE demo_cursor CURSOR FOR SELECT * FROM tbl_demo WHERE id=NEW.id;

然而,它不起作用,但在使用NEW.id这样的静态内容时工作正常

DECLARE demo_cursor CURSOR FOR SELECT * FROM tbl_demo WHERE id=5;

出了什么问题。

提前致谢

1 个答案:

答案 0 :(得分:1)

我无法重现这个问题。

mysql> DROP TABLE IF EXISTS `tbl_demo`, `result_demo`;
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE IF NOT EXISTS `tbl_demo` (
    ->   `id` INT,
    ->   `value` VARCHAR(50)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `result_demo` (
    ->   `id` INT,
    ->   `value` VARCHAR(50)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER //

mysql> CREATE TRIGGER `trg_after_insert` AFTER INSERT ON `tbl_demo`
    -> FOR EACH ROW
    -> BEGIN
    ->   DECLARE `done` BOOL DEFAULT FALSE;
    ->   DECLARE `_id` INT;
    ->   DECLARE `_value` VARCHAR(50);
    -> 
    ->   DECLARE `demo_cursor` CURSOR FOR
    ->   SELECT * -- <- SELECT `id`, `value` Recommendation for use
    ->   FROM `tbl_demo`
    ->   WHERE `id` = NEW.`id`;
    ->   DECLARE CONTINUE HANDLER FOR NOT FOUND SET `done` := TRUE;
    -> 
    ->   OPEN `demo_cursor`;
    -> 
    ->   `read_loop`: LOOP
    ->     FETCH `demo_cursor` INTO `_id`, `_value`;
    -> 
    ->     IF `done` THEN
    ->       CLOSE `demo_cursor`;
    ->       LEAVE `read_loop`;
    ->     END IF;
    -> 
    ->     INSERT INTO `result_demo`
    ->       (`id`, `value`)
    ->     VALUES
    ->       (`_id`, `_value`);
    ->   END LOOP;
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

mysql> INSERT INTO `tbl_demo`
    ->   (`id`, `value`)
    -> VALUES
    ->   (1, 'Value 1'),
    ->   (1, 'Value 2'),
    ->   (1, 'Value 3');
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT
    ->   `id`,
    ->   `value`
    -> FROM
    ->   `tbl_demo`;
+------+---------+
| id   | value   |
+------+---------+
|    1 | Value 1 |
|    1 | Value 2 |
|    1 | Value 3 |
+------+---------+
3 rows in set (0.00 sec)

mysql> SELECT
    ->   `id`,
    ->   `value`
    -> FROM
    ->   `result_demo`;
+------+---------+
| id   | value   |
+------+---------+
|    1 | Value 1 |
|    1 | Value 1 |
|    1 | Value 2 |
|    1 | Value 1 |
|    1 | Value 2 |
|    1 | Value 3 |
+------+---------+
6 rows in set (0.00 sec)