如果存在则创建或更改触发器

szp*_*pic 6 sql t-sql sql-server triggers

我正在尝试确定是否应该创建或更改并触发.我的代码如下.

IF OBJECT_ID(N'Sales.bonus_reminder', N'TR') IS NOT NULL
    ALTER TRIGGER Sales.bonus_reminder
    ON Sales.SalesPersonQuotaHistory
    AFTER INSERT
    AS RAISERROR ('Notify Compensation', 16, 10);
else
    CREATE TRIGGER Sales.bonus_reminder
    ON Sales.SalesPersonQuotaHistory
    WITH ENCRYPTION
    AFTER INSERT, UPDATE 
    AS RAISERROR ('Notify Compensation', 16, 10);
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

  • 其他附近的语法不正确
  • 创建触发器应该是批处理中唯一的语句.

这段代码应该如何?

Gor*_*off 10

如果您不希望将create trigger语句作为动态SQL,那么您可以执行以下操作:

IF OBJECT_ID(N'Sales.bonus_reminder', N'TR') IS NOT NULL
    exec sp_executesql N'DROP TRIGGER Sales.bonus_reminder';
GO

CREATE TRIGGER Sales.bonus_reminder
    ON Sales.SalesPersonQuotaHistory
    WITH ENCRYPTION
    AFTER INSERT, UPDATE 
    AS RAISERROR ('Notify Compensation', 16, 10);
Run Code Online (Sandbox Code Playgroud)


wor*_*yte 7

使用这个特别作为我的事实来源。这是简短的答案。

截至目前,您可以在某些数据库对象 ( // / ) 上使用语句而不是其他 drop 和 create 方法(我个人最喜欢的方法SQL Server 2016 sp1)。create or alterstored proceduresfunctionstriggersviews

所以你的脚本可能看起来像

create or alter TRIGGER Sales.bonus_reminder
    ON Sales.SalesPersonQuotaHistory
    WITH ENCRYPTION
    AFTER INSERT, UPDATE 
    AS RAISERROR ('Notify Compensation', 16, 10)
Run Code Online (Sandbox Code Playgroud)

  • 这里有更好的权威引用:https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2016 (4认同)