I am working on an audit requirement for a legacy application. The legacy application was written in Java using JDBC with an underlying DB in MySQL. I need to populate an audit table with any changes for a given table, the audit table DDL is something like this
CREATE TABLE ENTITY_AUD (
id INT AUTO_INCREMENT PRIMARY KEY,
baseTableId INT FK,
beforeValue INT,
afterValue INT,
changedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
changedBy VARCHAR2
);
I have to do this via triggers, since we want to avoid any changes to the legacy Java code. I know when can can know the old and new values of a given column by using the old and new variables, something like this
DELIMITER $$
CREATE TRIGGER ENTITY_AFTER_UPDATE
AFTER UPDATE
ON Entity FOR EACH ROW
BEGIN
IF OLD.quantity <> new.quantity THEN
INSERT INTO ENTITY_AUD(baseTableId,beforeValue, afterValue,changedBy)
VALUES(old.id, old.quantity, new.quantity,new.updated_by);
END IF;
END$$
DELIMITER ;
How can I dynamically find all the columns which have changed and populate new rows for each column updates? I do not want if statements for each column, the source tables may have 40 columns.