【问题标题】:SQL Update Trigger conditionalSQL 更新触发器条件
【发布时间】:2012-09-29 20:47:38
【问题描述】:

我正在研究 sql 中的触发器。我正在尝试执行更新触发器,但是我希望它仅在满足特定条件时才起作用。

例如,假设我有一个表 X 和两列 A、B。 我希望只有在 A 小于 B 时才能更新 A 或 B 以更新新值。

所以我正在做这样的触发器

create trigger utrigger
on X
for update as
if (update(A) OR update(B))
begin


 if (A>B)
 RAISERROR (N' Incorrect %s %d.', -- Message text.
       10, -- Severity,
       1, -- State,
       N'number', -- First argument.
       5); -- Second argument.

结束

但是我认为我做错了。这有什么问题?

【问题讨论】:

  • 此条件是否也适用于插入?如果 CHECK (B <= A) 上的检查约束应该应用于所有行,那么它的效率会更高。

标签: sql sql-server triggers


【解决方案1】:

您需要使用 INSERTED 虚拟表。

create trigger utrigger
on X
for update as
if (update(A) OR update(B))
begin
 if exists (SELECT *   -- this subquery breaches the condition
            FROM INSERTED
            WHERE A>=B)    -- might need some isnull if nulls are not allowed
 RAISERROR (N' Incorrect %s %d.', -- Message text.
       10, -- Severity,
       1, -- State,
       N'number', -- First argument.
       5); -- Second argument.
end

【讨论】:

    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    相关资源
    最近更新 更多