We have selected individual tables, as this will support your main table faster and faster. We also selected triggers, believing that if you ever change the input mechanism, you will not want to rewrite your audit. It can also record random changes away from the DBA.
Since updating is actually deleting and then pasting, you can achieve what was suggested with a single trigger - this is what we did.
Create a table that exactly matches your existing table, but with some columns added: AUDIT_GUID VARCHAR (40), AUDIT_TIMESTAMP DATETIME, AUDIT_ACTION VARCHAR (20)
Create a โAFTER INSERT, DELETE, UPDATEโ trigger using the following general template (just add more columns if necessary).
CREATE TRIGGER CustomerAudit ON Customer AFTER INSERT,DELETE,UPDATE AS BEGIN IF (TRIGGER_NESTLEVEL()>1) RETURN DECLARE @Time DateTime = CURRENT_TIMESTAMP DECLARE @Audit_GUID varchar(100) = NEWID() INSERT INTO Customer_History (FirstName, LastName, Audit_Date, Audit_Action, Audit_GUID) SELECT FirstName, LastName, @Time, 'Delete', @Audit_GUID FROM Deleted INSERT INTO Customer_History (FirstName, LastName, Audit_Date, Audit_Action, Audit_GUID) SELECT FirstName, LastName, @Time, 'Insert', @Audit_GUID FROM Inserted END
If you want to find updates, they will be rows in the history table that have deletion and update with the same Audit_GUID value. The timestamp also allows you to check for changes made at a specific time, and we also added currentuser to find the culprit in this case!
source share