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:
- Set the "Maximum trigger depth" to "2".
- I insert a row into table1
- A trigger on table1 inserts into table2
- A trigger on table2 inserts into table3
- 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).
Inside a trigger, you can check the nesting level, and optionally return:
See this blog post for more details.