创建SQL触发器以反转先前的触发器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建SQL触发器以反转先前的触发器相关的知识,希望对你有一定的参考价值。

我正在尝试创建多个触发器。当Crystal Reports更新同一表单中的(隐藏)字段“重新打印”时,一个触发器会更新“ysnAcknowledged”字段。如果用户手动更新“ysnAcknowledged”字段,则第二个触发器需要更新“重新打印”字段(表单复选框)。我有第一个触发器,我的问题是如果我更新'ysnAcknowledged'字段,它会触发我的第二个触发器,在我想要之前有效地反转第一个触发器。

第一次触发:

CREATE TRIGGER SOPickListReprint
ON dbo.SalesOrder
AFTER UPDATE
AS

IF UPDATE(Reprint)
UPDATE dbo.SalesOrder
SET ysnAcknowledged = 1

第二次触发:

CREATE TRIGGER SOPickListUpdate
ON dbo.SalesOrder
AFTER UPDATE
AS

IF UPDATE(ysnAcknowledged)
UPDATE dbo.SalesOrder
SET Reprint = 0
答案
CREATE TRIGGER SOPickListUpdate
    ON dbo.SalesOrder
    AFTER UPDATE
AS

-- Update only rows where Reprint changed or ysnAcknowledged changed
-- > If ysnAcknowledged changed, force Reprint to 0, otherwise leave it as it is
-- > If Reprint changed, force ysnAcknowledged to 1, otherwise leave it as it is
UPDATE
    SalesOrder
SET
    Reprint         = CASE WHEN inserted.ysnAcknowledged <> deleted.ysnAcknowledged THEN 1 ELSE inserted.Reprint END,
    ysnAcknowledged = CASE WHEN inserted.Reprint         <> deleted.Reprint         THEN 0 ELSE inserted.ysnAcknowledged END
FROM
    SalesOrder
INNER JOIN
    inserted
        ON  inserted.<primary_key> = SalesOrder.<primary_key>
INNER JOIN
    deleted
        ON  deleted.<primary_key>  = SalesOrder.<primary_key>
WHERE
       inserted.ysnAcknowledged <> deleted.ysnAcknowledged
    OR inserted.Reprint         <> deleted.Reprint
另一答案

我的解决方案

CREATE TRIGGER SOPickListReprint
ON dbo.SalesOrder
AFTER UPDATE
AS

UPDATE dbo.SalesOrder
SET ysnAcknowledged = CASE WHEN deleted.Reprint = 0 AND inserted.Reprint = 1 THEN 1 ELSE inserted.ysnAcknowledged END,
Reprint = CASE WHEN deleted.ysnAcknowledged = 1 AND inserted.ysnAcknowledged = 0 THEN 0 ELSE inserted.Reprint END
FROM SalesOrder
INNER JOIN
inserted
    ON  inserted.SalesOrderID = SalesOrder.SalesOrderID
INNER JOIN
deleted
    ON  deleted.SalesOrderID  = SalesOrder.SalesOrderID

以上是关于创建SQL触发器以反转先前的触发器的主要内容,如果未能解决你的问题,请参考以下文章

创建 SQL 触发器以更新另一个表时出错

如何创建触发器以将更改事件添加到审核日志表中

如何从 zapier 代码触发 webhook

片段创建的 Intent 不会触发 onNewIntent

SQL 创建触发器以在特定条件下更新表

sql 创建一个触发器以“清零”DATE数据类型的时间部分。