Question

Using SQL Server 2012, is it possible to have nested triggers enabled at the server/database level but to disable nesting on one specific table/trigger?

Était-ce utile?

La solution

I think that you should be able to achieve your purpose by using the TRIGGER_NESTLEVEL() function, which is available since SQL Server 2008:

Returns the number of triggers executed for the statement that fired the trigger. TRIGGER_NESTLEVEL is used in DML and DDL triggers to determine the current level of nesting.

You could alter the code of the relevant trigger to add the following statement just after the BEGIN keyword. The trick is to dynamically compute the object_id of the current trigger, which TRIGGER_NESTLEVEL() expects as first argument:

IF TRIGGER_NESTLEVEL(
    ( SELECT object_id FROM sys.triggers WHERE name = 'MyTrigger' )
) > 1 RETURN

This will actually prevent the given trigger to execute recursively.

Another option is to use TRIGGER_NESTLEVEL() without arguments. This returns the number of times all triggers have been executed for the statement. My understanding of your use case is that the first solution should be what you need.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top