简体   繁体   English

如何在 MySQL 触发器中传递动态表名和列名以保留在日志表中

[英]How to pass dynamic table name and column name to keep in log table in MySQL trigger

If a record is altered in a database table, I want to keep a record of all changes.如果数据库表中的记录被更改,我想保留所有更改的记录。 To do this, I want to enter the table name, column name, old value, and new value....... in the log table whenever an MYSQL table is changed via a trigger.为此,每当通过触发器更改 MYSQL 表时,我想在日志表中输入表名、列名、旧值和新值....... my log table look like我的日志表看起来像

在此处输入图像描述

You must define a trigger for a specific table, therefore you already know which table to use.您必须为特定表定义触发器,因此您已经知道要使用哪个表。 You can then specify it as a string literal when you write the trigger.然后,您可以在编写触发器时将其指定为字符串文字。

CREATE TRIGGER t AFTER UPDATE ON MyTable
FOR EACH ROW BEGIN
  IF NEW.column1 <=> OLD.column1 THEN
    INSERT INTO Log 
    SET table_name='MyTable', -- string literal
        field_name='column1', -- string literal
        old_val=OLD.column1,
        new_val=NEW.coumn1,
        action='UPDATE'; -- string literal
  END IF;
  IF NEW.column2 <=> OLD.column2 THEN
    INSERT INTO Log 
    SET table_name='MyTable', -- string literal
        field_name='column2', -- string literal
        old_val=OLD.column2,
        new_val=NEW.coumn2,
        action='UPDATE' -- string literal;
  END IF;
END

You'll have to continue and add another IF block for each column.您必须继续并为每列添加另一个 IF 块。

If you change the columns in your table, you'll have to rewrite the trigger.如果更改表中的列,则必须重写触发器。

You might ask if you can make one trigger that automatically does this for each column in a loop.您可能会问是否可以创建一个触发器,自动为循环中的每一列执行此操作。 No you can't do that.不,你不能那样做。 It would require PREPARE/EXECUTE, but you can't use dynamic SQL in a trigger.它需要准备/执行,但您不能在触发器中使用动态 SQL。

If this seems like a lot of work, you might want to consider using an audit plugin instead.如果这看起来工作量很大,您可能需要考虑使用审计插件 You can write your own, or you can use one of the open source audit plugins for MySQL , or if you're a customer of MySQL Enterprise, they offer an audit plugin to paying customers .您可以自己编写,也可以使用 MySQL 的开源审计插件之一,或者如果您是 MySQL Enterprise 的客户,他们会为付费客户提供审计插件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM