开发者

Get current updated column name to use in a trigger

Is there a way to actually get the column name that was updated in order to use it in a trigger?

Basically I'm trying to have an audit trail whenever a user inserts or updates a table (in this case it has to do with a Contact table)

CREATE TRIGGER `after_update_contact`
    AFTER UPDATE ON `contact` FOR EACH ROW
    BEGIN
        INSERT INTO user_audit (id_user, even_date, table_name, record_id, field_name, old_value, new_value)
        VALUES (NEW.updatedby, NEW.lastUpdate, 'contact', NEW.id_contact, [...])
    END

How can I get the name of the column that's been updated and from that get the OLD and NEW values of that column. If multiple columns have been upd开发者_StackOverflow中文版ated in a row or even multiple rows would it be possible to have an audit for each update?


Just use OLD.colname <> NEW.colname for each column to check and find those that are different. Triggers are a bit limited in their use in MySQL, too bad.


Try this code...

create table sales (
  orderno INT, 
  sale INT,
  empsalary int,
  ts TIMESTAMP
);

create table history (
  updated varchar(20),
  oldvalue INT,
  newvalue INT
);

INSERT INTO sales 
  (orderno, sale, empsalary) 
VALUES
  (1,700,7000),
  (2,800,8000),
  (3,900,9000);

DROP TRIGGER test.instrigger;

DELIMITER ///

CREATE TRIGGER test.instrigger
AFTER UPDATE ON sales
FOR EACH ROW

BEGIN

    IF NEW.sale <> OLD.sale THEN  
        INSERT INTO history
          (updated, oldvalue, newvalue) 
        VALUES
          ('sale', OLD.sale,NEW.sale);
    END IF;
  
    IF NEW.empsalary <> OLD.empsalary THEN  
        INSERT INTO history
          (updated, oldvalue, newvalue)
        VALUES
          ('empsalary', OLD.empsalary,NEW.empsalary);
    END IF;
END;
///

DELIMITER ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜