Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do triggers fire and when don't they

Pretty general question regarding triggers in SQL server 2005.

In what situations are table triggers fired and what situations aren't they?

Any code examples to demonstrate would be great.

I'm writing a audit based databases and just want to be aware of any situations that might not fire off the triggers that I have set up for update, delete and insert on my tables.

A example of what I mean,

UPDATE MyTable SET name = 'test rows' WHERE id in (1, 2, 3);

The following statement only fires the update trigger once.

like image 601
Nathan W Avatar asked Aug 09 '09 05:08

Nathan W


People also ask

Under what conditions does the trigger fire?

Any action type statement only fires the trigger once no matter how many rows are affected, triggers must be written to handle multiple row inserts/updates/deletes. If your trigger depends on only one row at a time being in the inserted or deleted pseudotables, it will fail.

Which trigger will fire first?

Constraint are always checked first in AFTER trigger, whereas BEFORE trigger fires first.

Can a trigger cause another trigger to fire?

This recursion occurs when a trigger fires and performs an action that causes another trigger of the same type (AFTER or INSTEAD OF) to fire. This second trigger performs an action that causes the original trigger to fire again.

What are 3 types of SQL triggers?

These are – INSERT, UPDATE, and DELETE.


2 Answers

When do you want them to fire?

CREATE TRIGGER AFTER ACTION

That runs after the action (insert update delete) being committed. INSTEAD OF fires the trigger in place of the action.

One of the biggest gotchas with triggers is that they fire whenever an action is performed, even if no rows are affected. This is not a bug, and it's something that can burn you pretty quickly if you aren't careful.

Also, with triggers, you'll be using the inserted and deleted tables. Updated rows are listed in both. This throws a lot of folks off, because they aren't used to thinking about an update as a delete then insert.

The MSDN documentation actually has a pretty in-depth discussion about when triggers fire and what effect they have here.

like image 66
Eric Avatar answered Oct 13 '22 05:10

Eric


On 2008 you can use built in Change Data Capture

Also There are quite a few situations when triggers do not fire, such as:

· A table is dropped.

· A table is truncated.

· Settings for nested and/or recursive triggers prevent a trigger from firing.

· Data is bulk loaded, bypassing triggers.

like image 34
A-K Avatar answered Oct 13 '22 04:10

A-K