我需要一种方法来检查并将条目传递到审核日志中,以查找已更改的表中的任何条目。它需要从表结构中抽象出来。
例如:
CREATE TRIGGER table1_update
BEFORE UPDATE ON table1
FOR EACH ROW BEGIN
DECLARE i_column_name varchar(32);
DECLARE done INT;
DECLARE cursor1 CURSOR FOR SELECT column_name FROM information_schema.columns WHERE table_name = 'table1';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cursor1;
REPEAT
FETCH cursor1 INTO i_column_name;
IF NOT done THEN
--pass the variable column_name and its old.i_column_name and new.i_column_name values to the audit table
END IF;
UNTIL done END REPEAT;
CLOSE cursor1;
END$$
我们有太多的表需要审核才能自定义构建每个INSERT,UPDATE和DELETE触发器。我尝试过很多东西,我觉得我运气不好。有人有什么想法吗?
答案 0 :(得分:1)
您不能拥有抽象触发器,必须在特定表上定义它。最接近的是将触发器的代码放入存储过程,然后每个表的触发器只调用该过程。
CREATE PROCEDURE audit_update (IN tablename VARCHAR(64))
BEGIN
DECLARE i_column_name varchar(32);
DECLARE done INT;
DECLARE cursor1 CURSOR FOR SELECT column_name FROM information_schema.columns WHERE table_name = tablename;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cursor1;
REPEAT
FETCH cursor1 INTO i_column_name;
IF NOT done THEN
--pass the variable column_name and its old.i_column_name and new.i_column_name values to the audit table
END IF;
UNTIL done END REPEAT;
CLOSE cursor1;
END
CREATE TRIGGER table1_update
BEFORE UPDATE ON table1
FOR EACH ROW BEGIN
CALL audit_update('table1');
END
您应该能够使用information_schema或类似的东西轻松编写将为您的所有表创建触发器的内容。
SELECT CONCAT('CREATE TRIGGER ', table_name, '_update BEFORE UPDATE ON ', table_name, ...) FROM information_schema...