【问题标题】:After trigger increasing value by 1 in all records instead of the only one being updated在所有记录中触发将值增加 1 而不是唯一更新的记录
【发布时间】:2018-07-06 14:59:03
【问题描述】:

我希望下面的触发器仅在客户地址已更改的行中将 NOA 列更新 +1。

我运行查询,只更新了一条记录中的客户地址,但所有 7 条记录中的 NOA 从 0 变为 1。怎么做?

create trigger track_updates
on CstmrEng.tblCustomer
after update
as
if (UPDATE(CustomerAddress))

update CstmrEng.tblCustomer
set NOA = NOA +1

【问题讨论】:

  • 如果真的只更改了一行,为什么您认为触发器会在所有行上运行?
  • 查看您的更新声明。当然它会更新整个表格。

标签: sql sql-server triggers sql-server-2016


【解决方案1】:

您应该始终在触发器中使用inserted

类似这样的:

create trigger track_updates
on CstmrEng.tblCustomer
after update
as
begin            
    if (UPDATE(CustomerAddress))
    begin
        update c
            set NOA = c.NOA + 1
            from CstmrEng.tblCustomer c join
                 inserted i
                 on c.customerId = i.customerId;  -- or whatever the primary key is
    end;
end;

【讨论】:

  • 谢谢!我越来越近了,但是我收到了这个错误:消息 209,级别 16,状态 1,过程 track_updates2,第 9 行 [批处理开始行 0] 不明确的列名“NOA”。 'NOA+1' 中的第二个 NOA 模棱两可,有什么办法解决吗?
猜你喜欢
  • 2021-10-16
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多