I've recently been given the task of creating an Audit on a database table so that any changes made to any columns can be tracked.
Lets say I have the following table:
[TableA]
------
ID
ColumnA
ColumnB
ColumnC
For Auditing I've created a table such as:
[TableA.Audit]
------
ID
TableAID
UserID
Date (default value = getdate())
ColumnA
ColumnB
ColumnC
I've then wrote a script like:
DECLARE @currentColumnA int
,@currentColumnB int
,@currentColumnC int
SELECT TOP 1 @currentColumnA=ColumnA
,@currentColumnB=ColumnB
,@currentColumnC=ColumnC
FROM [TableA]
WHERE ID=@TableAID
UPDATE [TableA]
SET ColumnA=@ColumnA
,ColumnB=@ColumnB
,ColumnC=@ColumnC
WHERE ID=@TableAID
INSERT INTO [TableA.Audit] (TableAID, UserID, ColumnA, ColumnB, ColumnC)
VALUES (@TableAID, @UserID, NULLIF(@ColumnA, @currentColumnA), NULLIF(@ColumnB, @currentColumnB), NULLIF(@ColumnC, @currentColumnC))
The problem with this, is that if I was to add a ColumnD
field to TableA
I'm going to have to edit my TableA.Audit
table as well as the above script.
Therefore is there a better way of doing this?