如何检查 MySQL 触发器中 OLD.* 到 NEW.* 列的差异?

How to check difference in each on OLD.* to NEW.* column in a MySQL Trigger?

由于SQL没有FOR-EACH语句,我们如何验证从OLD对象到NEW对象的每个值是否存在差异在 AFTER UPDATE 中键入 TRIGGER 而不知道 table 列 [和 table 名称]?

今天的例子:

CREATE TRIGGER `audit_events_ugly`
AFTER UPDATE ON `accounts`
FOR EACH ROW
BEGIN
       DECLARE changes VARCHAR(8000);
       IF OLD.user_name <> NEW.user_name THEN
            SET changes = 'user_name from % to %';
       END IF;
       IF OLD.user_type <> NEW.user_type THEN
            SET changes = CONCAT(changes, ', user_type from % to %');
       END IF;
       IF OLD.user_email <> NEW.user_email THEN
            SET changes = CONCAT(changes, ', user_email from % to %');
       END IF;
       CALL reg_event(how_canI_get_tableName?, @user_id, changes);
       -- and that can go on and on... differently for every table.
END;

示例如我所愿:

CREATE TRIGGER `audit_events_nice`
AFTER UPDATE ON `accounts`
FOR EACH ROW
BEGIN
       DECLARE changes VARCHAR(8000);
       DECLARE N INT DEFAULT 1;
       FOREACH OLD, NEW as OldValue, NewValue 
       BEGIN
              IF OldValue <> NewValue THEN
              SET changes = CONCAT(changes, ', column N: % to %');
              SET N = N + 1;
       END IF;
       CALL reg_event(how_canI_get_tableName?, @user_id, changes);
       -- now I can paste this code in every table that is audited..
END;

有什么想法吗?同时,FOREACH,数组...

我认为你不能在触发器级别的 for 循环中直接这样做。

但是,您可以使用脚本来生成触发代码。每次 add/remove 一个字段到 table 时,您都需要重新生成它(通常不经常)。