SQL Insert/Update/Delete Trigger Efficiency

亡梦爱人 提交于 2020-01-04 14:02:14

问题


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


回答1:


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.




回答2:


Create one trigger for INSERTs and UPDATEs and a second for DELETEs. Then you don't have to use an IF statement and a slow query to check where to log.

From a design perspective, see if you can eliminate triggers. They're a mess.




回答3:


Well you could make this simple change:

Create TRIGGER [Billing].[Installments_InsertDeleteUpdate_History]
ON [Billing].[Installments]
AFTER INSERT, DELETE, UPDATE
AS BEGIN

If Not Exists (Select * From Inserted)
    Insert Into Billing_History.Installments
        Select *, GetDate(), 1 From Deleted
ELSE
    Insert Into Billing_History.Installments
        Select *, GetDate(), 0 From Inserted

SET NOCOUNT ON;

-- Insert statements for trigger here

Which is logically more efficient, but whether it's physically more performant is an open question. If it is actually faster, it sure won't be by very much.



来源:https://stackoverflow.com/questions/12629279/sql-insert-update-delete-trigger-efficiency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!