简体   繁体   中英

Getting trigger to insert changed column values only in audit table

I'm using a trigger to store changes in an audit table, I only want to store the values from columns that have been changed.

BEGIN
IF NEW.history_of_repair_trigger_fired = 1 THEN
INSERT INTO history_of_repair SET
edit_date_time=NEW.last_edited_date_time,
edited_by=NEW.edited_by,
repair_id=NEW.repair_id,
tenant_name=NEW.tenant_name,
property_id=NEW.property_id,
priority=NEW.priority,
comments=NEW.comments,
signed_off=NEW.signed_off;
END IF;
END

At the moment this is storing the unchanged values in the audit table too, which is not desirable.

What's the best way of only storing the changed columns in my audit table?

Based on your comments, I wouldn't be concerned about storing only the changed values -- disk space is cheap. Storing the actual values has the advantage that it makes it trivial to restore a record to a point in time if you need to in a hurry. If you need to produce a human-readable audit record, then store it in a varchar/nvarchar and construct the message in your trigger by accumulating the changes into a string. I might store this in addition to the actual values. Note that you could also provide a table-valued function which dynamically constructs this human readable column for you rather than storing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM