The insertion of the history table will occur only in case of a change in Attribute3 .
try it
CREATE TRIGGER [dbo].[tr_UpdateResourceHistoryVersionId] ON [dbo].[TableResources] INSTEAD OF UPDATE AS SET NOCOUNT ON; BEGIN IF EXISTS(SELECT 1 FROM inserted i JOIN deleted d ON i.ID = d.ID AND i.Attribute3 = d.Attribute3) BEGIN UPDATE T SET VersionId = inserted.VersionId, Attribute1 = inserted.Attribute1, Attribute2 = inserted.Attribute2 FROM Inserted I JOIN [TableResources] T ON I.ID = T.ID JOIN deleted d ON i.ID = d.ID AND i.Attribute3 = d.Attribute3 END IF EXISTS(SELECT 1 FROM inserted i JOIN deleted d ON i.ID = d.ID AND i.Attribute3 <> d.Attribute3) BEGIN INSERT TableResourceHistory (Attribute3History,HistoryDate,VersionId) SELECT Newid(), Getutcdate(), d.VersionId FROM deleted d JOIN Inserted i ON i.ID = d.ID AND i.Attribute3 <> d.Attribute3
If something goes wrong or doesn't work as expected, go back to the comments section below this answer
source share