有没有办法实际获取已更新的列名,以便在触发器中使用它?
基本上,每当用户插入或更新表时,我都会尝试使用审计跟踪(在这种情况下,它与Contact表有关)
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
如何获取已更新的列的名称,并从中获取该列的OLD
和NEW
值。如果连续更新了多列甚至多行,是否可以对每次更新进行审核?
答案 0 :(得分:8)
只需使用OLD.colname<>每个列的NEW.colname用于检查和查找不同的列。触发器在MySQL中的使用有点受限,太糟糕了。
答案 1 :(得分:2)
试试这段代码......
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);
INSERT INTO sales (orderno,sale,empsalary) VALUES(2,800,8000);
INSERT INTO sales (orderno,sale,empsalary) VALUES(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 ;