[英]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: 我的想法是有一个名为“changelog_table”的表,其中包含以下列:
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. 因此,假设我有一个名为“foo_table”的表,其中一列“bar_column”,行“58008”,正在被用户“peter_griffin”更新为“这是新内容”,时间为12/30 / 2013年中午。
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). 您需要在每个表上为
UPDATE
创建单独的触发器(如果需要,也需要为INSERT
和DELETE
)。 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. 要检测哪些列已更新,您需要在每个触发器中对相应表中每列的
NEW.column
和OLD.column
进行比较。
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(),
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.