Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Why does a CREATE TRIGGER need to be preceded by GO

When making a SQL script to create a trigger on a table, I wanted to check that the trigger doesn't already exist before I create it. Otherwise the script cannot be run multiple times.

So I added a statement to first check whether the trigger exists. After adding that 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 would be to drop the existing trigger and then create the 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 is the first example failing? What is so wrong with checking the trigger exists?

like image 933
demoncodemonkey Avatar asked Jan 31 '12 17:01

demoncodemonkey


2 Answers

Certain statements need to be the first in a batch (as in, group of statements separated by GO ).

Quote:

CREATE DEFAULT, CREATE FUNCTION, CREATE PROCEDURE, CREATE RULE, CREATE SCHEMA, CREATE TRIGGER, and CREATE VIEW statements cannot be combined with other statements in a batch. The CREATE statement must start the batch. All other statements that follow in that batch will be interpreted as part of the definition of the first CREATE statement.

like image 156
Stu Avatar answered Sep 28 '22 13:09

Stu


It's simply one of the rules for SQL Server batches (see):

http://msdn.microsoft.com/en-us/library/ms175502.aspx

Otherwise you could change an object, say a table, and then refer to the change in the same batch, before the change was actually made.

like image 43
Mithrandir Avatar answered Sep 28 '22 11:09

Mithrandir