I have a requirement to keep a history of changes made to a specific table when UPDATE is called, but they only care about specific columns.
So, I created the History table:
CREATE TABLE [dbo].[SourceTable_History]( [SourceTable_HistoryID] [int] IDENTITY(1,1) NOT NULL, [SourceTableID] [int] NOT NULL, [EventDate] [date] NOT NULL, [EventUser] [date] NOT NULL, [ChangedColumn] VARCHAR(50) NOT NULL, [PreviousValue] VARCHAR(100) NULL, [NewValue] VARCHAR(100) NULL CONSTRAINT pk_SourceTable_History PRIMARY KEY ([SourceTable_HistoryID]), CONSTRAINT fk_SourceTable_HistoryID_History_Source FOREIGN KEY ([SourceTableID]) REFERENCES SourceTable (SourceTableId) )
Abd my plan is to create an update trigger in SourceTable. Business only cares about changes in certain columns, so in the psudo code I planned to do something like
If source.Start <> new.start Insert into history (PrimaryKey, EventDate, EventUser, ColumnName, OldValue, NewValue) (PK, GETDATYE(), updateuser, "StartDate", old.value, new.value)
And there will be a block similar to this column in which we want to include the story.
We are NOT allowed to use CDC, so we have to minimize it ourselves, and this is my plan.
Does this sound like a suitable plan?
There are 7 tables that we need to track, with the number of columns from 2 to 5 columns per table.
I just need to figure out how to get the trigger for the first comapr before and after the values ββof a specific column, and then write a new row.
I thought it was simple:
CREATE TRIGGER tr_PersonInCareSupportNeeds_History ON PersonInCareSupportNeeds FOR UPDATE AS BEGIN IF(inserted.StartDate <> deleted.StartDate) BEGIN INSERT INTO [dbo].[PersonInCareSupportNeeds_History] ([PersonInCareSupportNeedsID], [EventDate], [EventUser], [ChangedColumn], [PreviousValue], [NewValue]) VALUES (inserted.[PersonInCareSupportNeedsID], GETDATE(), [LastUpdateUser], 'StartDate', deleted.[StartDate], deleted.[StartDate]) END END