MySQL触发器 Update触发Insert失败
时间:2021-05-15 09:08:11|栏目:Mysql|点击: 次
今天工作需要,想要实现将仅对状态更新的表进行历史记录显示,于是考虑在原表中建立触发器,将更新的内容同时写入另一张表
于是进行测试
--建立测试表CREATE TABLE `triggletest_triggle` ( `id` INT(11) NOT NULL, `name` VARCHAR(5) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB --建立目标表 CREATE TABLE `triggletest` ( `seq` INT(11) NOT NULL, `id` INT(11) NOT NULL, `name` VARCHAR(5) NULL DEFAULT NULL, PRIMARY KEY (`seq`), INDEX `id` (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB; ---写入测试数据 INSERT INTO `triggletest_triggle` VALUES(1,'A'); --建立触发器 DROP TRIGGER if EXISTS test1 CREATE TRIGGER test1 AFTER UPDATE ON triggletest_triggle FOR EACH ROW BEGIN INSERT INTO triggletest(id) values (new.id); END
执行触发器语句,报错,报错内容如下:
/* SQL错误(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 'CREATE TRIGGER test1 AFTER UPDATE ON triggletest_triggle FOR EACH ROW BEGIN ' at line 2 */ ---最终实现代码 DROP TRIGGER if EXISTS test1; CREATE TRIGGER test1 AFTER UPDATE ON test.triggletest_triggle FOR EACH ROW BEGIN INSERT INTO triggletest(id,name) values (new.id,new.name); END;
分析,由于访问工具HediSQL,导致无法正常创建触发器,相同语句,在HediSQL中执行,报错,使用shell调用mysql,直接执行程序,成功。