When creating an SQL script to create a trigger in a table, I would like to verify that the trigger does not exist before it is created. Otherwise, the script cannot be executed multiple times.
So, I added an instruction to first check if a trigger exists. After adding this statement, the CREATE TRIGGER statement no longer works.
IF NOT EXISTS (SELECT name FROM sysobjects WHERE name = 'tr_MyTable1_INSERT' AND type = 'TR') BEGIN CREATE TRIGGER tr_MyTable1_INSERT ON MyTable1 AFTER INSERT AS BEGIN ... END END GO
This gives:
Msg 156, Level 15, State 1, Line 5 Incorrect syntax near the keyword 'TRIGGER'.
The solution is to delete the existing trigger and then create a new one:
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'tr_MyTable1_INSERT' AND type = 'TR') DROP TRIGGER tr_MyTable1_INSERT GO CREATE TRIGGER tr_MyTable1_INSERT ON MyTable1 AFTER INSERT AS BEGIN ... END GO
My question is : why does the first example not work? What is wrong with trigger checking?
source share