I have a large table in a database and I want to track changes made to the individual records. More precisely, I want to log the date and the changes made to the columns.
Since the table has 25+ comlumns I don’t want to test them individually.
The logging table looks like ID-Date-Table-Column-OldValue-NewValue
In my AFTER UPDATE trigger I’d like to check which columns have different values and log them into my table.
I know I can get the columns of the table with:
DECLARE @meta_table TABLE (
idx smallint Primary Key IDENTITY(1,1)
, TABLE_NAME nchar(100), COLUMN_NAME nchar(100), COLUMN_ID int
)
INSERT @meta_table
SELECT TABLE_NAME, COLUMN_NAME,
COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME),
COLUMN_NAME, 'ColumnID') AS COLUMN_ID
FROM MYDATABASE.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTable';
I can iterate the columns with:
SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM @meta_table)
IF @numrows > 0
WHILE (@i <= (SELECT MAX(idx) FROM @meta_table))
BEGIN
SET @col = (SELECT COLUMN_NAME FROM @meta_table WHERE idx = @i)
-- do something with @col
SET @i = @i + 1
END
In a first step I’d like to check all columns but something like this does not work
IF (SELECT @col FROM inserted) <> (SELECT @col FROM deleted)
BEGIN
-- INSERT into logging table ...
END
Additionally that would only check the first row of updates, so I would need to do that for each row in the deleted/inserted table.
Change Data Capture can be a solution to log table DML changes.