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

Posted

技术标签:

【中文标题】关键字“TRIGGER”附近的 T-SQL 语法不正确【英文标题】:T-SQL Incorrect syntax near the keyword 'TRIGGER' 【发布时间】:2017-10-27 06:38:22 【问题描述】:

我创建而不是这样的触发器:

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”附近的语法不正确。

我也尝试了 IF 与 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;

为什么我得到这个错误? :-)

【问题讨论】:

应该帮助你...***.com/questions/28225329/… 请特别注意,CREATE TRIGGER 必须是批处理中的第一个语句。 【参考方案1】:

标准结构

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

【讨论】:

【参考方案2】:

试试这个

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;

【讨论】:

@Yogesh Sharma “表格”附近的语法不正确。却是那么接近解决。当我删除 RAISEERROR 语句时,它很好。转义(?)'字符的问题,在错误的字符上关闭 exec 命令。工作代码但没有 raiseerror code IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'TR' AND name = 'CRMTelefonRekorduKampaniiReadOnlyEvent') BEGIN EXEC ('CREATE TRIGGER ReadOnlyEvent ON CRMTelefonRekorduKampanii INSTEAD OF INSERT, UPDATE, DELETE AS BEGIN ROLLBACK交易结束'); END;`代码'【参考方案3】:

试试这个

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

【讨论】:

以上是关于关键字“TRIGGER”附近的 T-SQL 语法不正确的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 附近的语法不正确

关键字“FOR”XML 附近的语法不正确

执行 T-SQL UNION 语句时出错。有啥解释吗?

错误“关键字 'CONVERT' 附近的语法不正确”

关键字“read”附近的语法不正确

在关键字“pivot”附近出现语法错误,提示语法不正确。我在这里想念啥