Problem
I have a trigger created on the table that will be activated when a insert,delete or UPDATE statement is executed against the table. I want to prevent a trigger from being activated on a particular statement, and the trigger remains in a normal state of execution when other statements are executed. Is there a way to do this dynamically?
Expert answers
At some point, disabling triggers is something you might need to do, especially if you are performing an administrator task on a single table. The best way to achieve this is to use the following command to completely deactivate the trigger.
ALTER TABLE Table_Name DISABLE TRIGGER Trigger_Name
However, if you only want to deactivate a trigger on a particular statement, there is no default mechanism to do this unless you develop a programmable method of your own. Use this method to deactivate a trigger only on a particular statement, and the trigger continues to be activated on a statement that clicks on the server at the same time.
Even if there are many ways to implement it, the main logic is to pass some signals to the trigger, telling the trigger that you do not need to activate it to execute.
Use a temporary table
The easiest way to accomplish this task is to create a temporary table before you execute the statement that activates the trigger. Now this trigger will check whether the temp table exists, and if the temporary table exists, the trigger will return and not execute the code, otherwise it will execute its code as usual.
To see the execution process, let's run the following statement to create a table and a trigger.
USE AdventureWorks;
GO
-- creating the table in AdventureWorks database
IF OBJECT_ID('dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1
GO
CREATE TABLE dbo.Table1(ID INT)
GO
-- Creating a trigger
CREATE TRIGGER TR_Test ON dbo.Table1 FOR INSERT,UPDATE,DELETE
AS
IF OBJECT_ID('tempdb..#Disable') IS NOT NULL RETURN
PRINT 'Trigger Executed'
-- Actual code goes here
-- For simplicity, I did not include any code
GO