MySQL触发器:INSERT ON日志BEFORE DELETE ON表

时间:2015-02-02 20:08:41

标签: mysql database triggers

这是我的第一篇帖子! =]

每当有人试图从表中删除某些内容时,我都会创建一个插入日志表的触发器

CREATE DEFINER=`root`@`localhost` TRIGGER `user_before_delete`      
BEFORE DELETE ON `user` FOR EACH ROW BEGIN

INSERT INTO log_alert(id, table_id, name)
VALUES('99002', OLD.id, OLD.name);

SIGNAL SQLSTATE '99002'
SET MESSAGE_TEXT = 'TRYING TO REMOVE A USER!'
END

但问题是: SIGNAL SQLSTATE回滚整个操作! 那么,如何通过DELETING用户来插入LOG TABLE和PREVENTE?

2 个答案:

答案 0 :(得分:2)

Marc B的解决方法为我工作=]

quick/dirty workaround: change log_alert to be a myisam table. no transactions there, so no way to roll back your insert. –  Marc B 15 hours ago

只需将 log_alert 更改为MyISAM类型,INSERTS就不会再回滚

答案 1 :(得分:0)

在使用BEGIN/END阻止之前,将分隔符更改为$$,然后切换回:

DELIMITER $$

CREATE DEFINER=`root`@`localhost` TRIGGER `user_before_delete`      
BEFORE DELETE ON `user` FOR EACH ROW BEGIN

INSERT INTO log_alert(id, table_id, name)
VALUES('99002', OLD.id, OLD.name);

SIGNAL SQLSTATE '99002'
SET MESSAGE_TEXT = 'TRYING TO REMOVE A USER!';

END $$

DELIMITER ;

试一试!!!