T-SQL关键字' TRIGGER'附近的语法不正确

时间:2017-10-27 06:38:23

标签: sql sql-server tsql triggers

我创造了而不是像这样的触发器:

CREATE TRIGGER ReadOnlyEvent ON 
TableName INSTEAD OF INSERT, UPDATE, DELETE AS BEGIN 
RAISERROR('Tables are read only.', 16, 1 ) ROLLBACK TRANSACTION END;

该代码工作正常。但是,当我将其与“' IF'我收到了一个错误:

 IF OBJECT_ID ('ReadOnlyEvent', 'TR') IS NULL 
    CREATE TRIGGER ReadOnlyEvent ON
 TableName INSTEAD OF INSERT, UPDATE, DELETE AS BEGIN 
 RAISERROR('Tables are read only.', 16, 1 ) ROLLBACK TRANSACTION END;
  

关键字' TRIGGER'附近的语法不正确。

我还尝试使用BEGIN END:

IF OBJECT_ID ('ReadOnlyEvent', 'TR') IS NULL
BEGIN
    CREATE TRIGGER ReadOnlyEvent ON
    TableName INSTEAD OF INSERT, UPDATE, DELETE AS BEGIN 
    RAISERROR('Tables are read only.', 16, 1 ) ROLLBACK TRANSACTION END;
END;

为什么我收到此错误? : - )

3 个答案:

答案 0 :(得分:2)

标准建筑

IF OBJECT_ID ('ReadOnlyEvent', 'TR') IS NOT NULL 
DROP TRIGGER dbo.ReadOnlyEvent
GO
CREATE TRIGGER dbo.ReadOnlyEvent ON
  TableName INSTEAD OF INSERT, UPDATE, DELETE AS BEGIN 
RAISERROR('Tables are read only.', 16, 1 ) ROLLBACK TRANSACTION END;
GO

答案 1 :(得分:1)

试试这个

IF NOT EXISTS ( SELECT  *  FROM    sys.objects WHERE   type = 'TR'
                    AND name = 'ReadOnlyEvent' ) 

BEGIN
    EXEC ('CREATE TRIGGER ReadOnlyEvent ON
    TableName INSTEAD OF INSERT, UPDATE, DELETE AS BEGIN 
    RAISERROR('Tables are read only.', 16, 1 ) ROLLBACK TRANSACTION END');
END;

答案 2 :(得分:0)

试试这个

BEGIN 
    IF OBJECT_ID ('ReadOnlyEvent', 'TR') IS NULL 
        BEGIN
            CREATE TRIGGER ReadOnlyEvent ON
            TableName INSTEAD OF INSERT, UPDATE, DELETE AS BEGIN 
            RAISERROR('Tables are read only.', 16, 1 ) ROLLBACK TRANSACTION END;
        END 
END