In our application at the database level, I have a table called Installments in schema Billing and Billing_History.
The trigger shown is on the Installments table in the Billing Schema.
What this does is everytime a record is inserted/updated in the billing schema it is also written into the history file.
If the record is deleted from the billing table it is written to the history table with a “Deleted” indicator = true.
I think that the “If Not Exists (Select * from Inserted) is killing my performance as more records get added.
Is there a more effecient was to write this trigger?
Create TRIGGER [Billing].[Installments_InsertDeleteUpdate_History]
ON [Billing].[Installments]
AFTER INSERT, DELETE, UPDATE
AS BEGIN
Insert Into Billing_History.Installments
Select *, GetDate(), 0 From Inserted
If Not Exists (Select * From Inserted)
Insert Into Billing_History.Installments
Select *, GetDate(), 1 From Deleted
SET NOCOUNT ON;
-- Insert statements for trigger here
END
I would suggest that the trigger form you have is the best performing, given it’s required tasks. There really aren’t much better ways to achieve the same auditing result.
The answer here would agree Creating audit triggers in SQL Server and here’s a long discussion about performance of audit solutions.
Your situation is slightly different, because you actually DON’T want the deleted (original) table in UPDATE situations, hence the IF.