简体   繁体   中英

In mySQL, how do I make a Trigger so that one table keeps a change log from ALL other tables?

My idea was to have a table called "changelog_table" that had the following columns:

updated_table     //the table being updated
updated_column    //the column being updated
updated_row       //the id of the row being updated
updated_content   //this is what they updated the field to
updated_user      //the user who updated
updated_datetime  //the timestamp it was updated

I think this is both the minimum and maximum of what I'd really want, but I may be wrong. Also...I do not understand, after weeks of reading, how to store variables (like "which table is being updated" and "which column is being updated" and so forth) in my trigger.

So let's say I had a table called "foo_table", with a column "bar_column", with a row "58008", that is being updated to "this is the new content", by user "peter_griffin", at 12/30/2013 at noon.

What would a trigger that could capture that look like?

You'll need to create separate triggers on each table for UPDATE (and, if so desired, for INSERT and DELETE too). They could each call the same stored procedure that does the actual logging.

The trigger can pass to the stored procedure a parameter containing the name of the table on which the operation is being performed (since the trigger is table-specific, it will know this - it'll have to be hardcoded); to detect which column(s) have been updated you'll need to compare, within each trigger, NEW.column with OLD.column for each column in the respective table.

For example:

CREATE TRIGGER upd_tbl_name AFTER UPDATE ON tbl_name FOR EACH ROW
  CALL AuditLog('UPDATE', 'tbl_name', NEW.id, CONCAT_WS(',',
    IF(NEW.columnA <=> OLD.columnA, NULL, CONCAT('columnA:=', NEW.columnA)),
    IF(NEW.columnB <=> OLD.columnB, NULL, CONCAT('columnB:=', NEW.columnB)),
    -- etc.
  ));

CREATE PROCEDURE AuditLog(
  Action VARCHAR(10),
  TableName VARCHAR(64),
  RowID INT,
  Columns TEXT,
)
  INSERT INTO changelog_table VALUES (
    Action,
    TableName,
    RowID,
    Columns
    USER(),
    NOW(),
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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