Can I have two different insert triggers on the same table?
Solution 1
Yes, you can definitely have more than one trigger for each operation, e.g. AFTER INSERT
or AFTER UPDATE
etc. It does make sense to split up separate concerns into separate, small, manageable chunks of code.
The one thing you cannot rely on is that they'll be executed in a certain order - the order in which the triggers are indeed executed also doesn't have to be stable, i.e. the same every time around.
Solution 2
it's a good practice because then you can break down your changes over time into little (agile) chunks and add or remove them independently of each other.
Related videos on Youtube
Hammad Khan
Humble, down to earth, experience software Engineer 12+ years of industry experience in ASP.NET, SQL Server, C/C++, Web Development, Automation
Updated on November 12, 2020Comments
-
Hammad Khan over 3 years
They seem to be allowed as I can see both my insert triggers listed under the table with different names. Is it common or a bad practice? I am using SQL Server 2005
-
Martin Smith over 12 yearsWhat do the triggers do? The
INSERTED
table is not indexed so for performance reasons it might be better to consolidate them.
-
-
Hammad Khan over 12 yearsBTW if I insert 2 or more rows at a time (basically I am importing a bunch of records), is there a way I can reference EACH insert, or the trigger is automatically executed for every single insert?
-
Andrew Lazarus over 12 yearsDepends on RDBMS. Postgres guarantees multiple triggers are called in alpha order of name. They state SQL Standard (seldom followed) is in order of creation.
-
marc_s over 12 years@AndrewLazarus: I was referring to SQL Server (since the OP asked about that), and SQL Server doesn't have any such capability. Thanks for pointing that out!
-
Andrew Lazarus over 12 yearsAbsolutely. I often add notes like that figuring people land here from Google a lot.
-
Martin Smith over 12 yearsThough you can use
sp_settriggerorder
to set first and last trigger. -
Niraj over 9 years@hmd trigger will be automatically executed for every single insert untill and unless you are using bulk inserts in which trigger will be executed once for each bulk insert command.
-
olf over 6 yearsKnow it is an old question! In your trigger you can always reference a table called "inserted" which contains all the rows you have just inserted (being one or more rows on an insert trigger). And by creating cursors you can loop through each of your rows and do stuff to them if you want.