更新后的mysql触发器选择多列多行

时间:2016-03-31 11:10:14

标签: mysql

DELIMITER //
CREATE TRIGGER `enclosure-after_update-time` AFTER UPDATE ON `enclosure`
 FOR EACH ROW BEGIN
    IF NEW.time <> OLD.time THEN
        DECLARE done INT DEFAULT FALSE;
        DECLARE ids INT;
        DECLARE invoice_ids INT;
        DECLARE cur CURSOR FOR SELECT id AS ids, invoice_id AS invoice_ids FROM accounting WHERE enclosure_id = NEW.id;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

        OPEN cur;
            ins_loop: LOOP
                FETCH cur INTO ids, invoice_ids;
                IF done THEN
                    LEAVE ins_loop;
                END IF;
                UPDATE accounting SET time=NEW.time WHERE id=ids;
                IF invoice_ids THEN
                    UPDATE invoice SET time=NEW.time WHERE id=invoice_ids;
                END IF;
            END LOOP;
        CLOSE cur;
    END IF;
END
//
DELIMITER ;

错误

#1064 - 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 done INT DEFAULT FALSE;
        DECLARE ids INT;
        DECLARE invoi' at line 4

1 个答案:

答案 0 :(得分:0)

在最开始声明你的变量

DELIMITER //
CREATE TRIGGER `enclosure-after_update-time` AFTER UPDATE ON `enclosure`
 FOR EACH ROW BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE ids INT;
    DECLARE invoice_ids INT;
    DECLARE cur CURSOR FOR SELECT id, invoice_id INTO ids, invoice_ids FROM accounting WHERE enclosure_id = NEW.id;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    IF NEW.time <> OLD.time THEN
        OPEN cur;
            ins_loop: LOOP
                FETCH cur INTO ids, invoice_ids;
                IF done THEN
                    LEAVE ins_loop;
                END IF;
                UPDATE accounting SET time=NEW.time WHERE id=ids;
                IF invoice_ids THEN
                    UPDATE invoice SET time=NEW.time WHERE id=invoice_ids;
                END IF;
            END LOOP;
        CLOSE cur;
    END IF;
END
//
DELIMITER ;