Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger being called on all rows in database

Tags:

sql

tsql

I have written a trigger that I want to use for adding the date to a column in a record so that I can keep track of the insert of the item.

There are a large amount of inserts being called (about 20000) and I have noticed that the trigger will update all of the InsertDate columns associated with each item every time a new item is added. How can I make sure this happens to an item being inserted only one time.

My trigger is as follows:

 SET ANSI_NULLS ON
 SET QUOTED_INDENTIFIER ON
 GO


 CREATE TRIGGER [InsertDate_Item]
    ON [dbo].[ItemHolder]
    AFTER INSERT
    NOT FOR REPLICATION
 AS
 UPDATE ItemHolder SET InsertDate = GETDATE()

Any help will be much appreciated.

Thanks

like image 582
rinnanstimpy Avatar asked Dec 16 '22 12:12

rinnanstimpy


2 Answers

You need to restrict rows to those inserted... using the virtual trigger table INSERTED

 CREATE TRIGGER [InsertDate_Item]
    ON [dbo].[ItemHolder]
    AFTER INSERT
    NOT FOR REPLICATION
 AS
 SET NOCOUNT ON
 UPDATE IH
 SET InsertDate = GETDATE()
 FROM
    ItemHolder IH
    JOIN
    INSERTED INS ON IH.keycol = INS.keycol
 Go

One thing: You'd be better adding a default to the table instead. No need for a trigger

ALTER TABLE ItemHolder ADD
CONSTRAINT DF_ItemHolder_InsertDate DEFAULT (GETDATE()) FOR InsertDate
like image 157
gbn Avatar answered Dec 19 '22 08:12

gbn


If you are inserting records into a table, why don't you make the InsertDate field have a default value of GetDate()? That avoids the trigger altogether.

like image 45
IAmTimCorey Avatar answered Dec 19 '22 07:12

IAmTimCorey