views:

140

answers:

1

I know about "Allow Triggers to Fire Others" server setting that allows the action taken by a trigger to fire another trigger (or not), and as I understand it, my only options are True (allow trigger to fire other triggers, which may lead to unending recursion) or False (actions taken by triggers will not fire any other triggers, which may lead to unexpected results or inconsistent data).

Is there a way to enforce a "Maximum trigger depth" in SQL Server? I'm using 2008, if it matters, though I'm not aware of the feature on any version (or in any other RDBMS, for that matter, though my knowledge is admittedly limited). For example, here's what I'd like:

  1. Set the "Maximum trigger depth" to "2".
  2. I insert a row into table1
  3. A trigger on table1 inserts into table2
  4. A trigger on table2 inserts into table3
  5. There's a trigger on table3 that would insert into table4, but since the maximum depth is 2, either the trigger just doesn't get run (less ideal, but consistent with current "Recursive triggers=False" behavior on SQL Server), or the whole set of inserts is rolled back and fails with an error like "Maximum trigger depth (2) exceeded - insert failed" message (ideal)

Does anybody out there know if this is possible, or if there's an outstanding feature request for this behavior? If I'm crazy and this is a terrible idea for behavior, I'm open to that, but I'd like to know why (unintentional consequences, etc).

+2  A: 

Inside a trigger, you can check the nesting level, and optionally return:

IF (TRIGGER_NESTLEVEL() > 2)
    RETURN

See this blog post for more details.

Andomar
exec sp_CONFIGURE 'nested_triggers' can take values 0 or 1 only.
Lukasz Lysik
@Lukasz Lysik: You're right, post edited
Andomar
That blog post is exactly what I was looking for - thanks. I can't believe I didn't know about this feature
rwmnau