如何在插入触发器之后在条件库上声明游标(Mysql)

时间:2016-07-08 05:12:14

标签: mysql triggers cursor

我的触发器在这里。

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//

我希望根据NEW字段值声明 demo_cusror ,例如

if NEW.`id`=NULL THEN
   DECLARE `demo_cursor` CURSOR FOR SELECT * tbl_demo ;
ELSE
   DECLARE `demo_cursor` CURSOR FOR SELECT * tbl_demo2;
END IF

我试过,但我不能把条件放在声明部分。

1 个答案:

答案 0 :(得分:0)

你不能在mysql中有条件地声明任何变量。期。正如declare上的mysql文档所说:

  

DECLARE只允许在BEGIN ... END复合语句中使用,并且必须在任何其他语句之前的开头。

声明2个游标变量并在应用程序逻辑中决定使用哪个。