在某些情况下禁用更新触发器

发布于 2024-11-05 20:31:49 字数 70 浏览 0 评论 0原文

我编写了一个更新触发器,因此每次更新发生时触发器都会运行。 但仅对于我的更新语句之一,我不希望触发发生。 如何暂时禁用触发器?

I have written an trigger for update, so every time an update occurs the trigger will run.
but just for one of my update statements I don't want the trigger happens.
how can I disable trigger temporarily?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

倚栏听风 2024-11-12 20:31:49

MSDN has an example of how to use CONTEXT_INFO to disable a trigger for a single session only.

冰火雁神 2024-11-12 20:31:49

使用禁用触发器语句,然后按如下方式进行更新

DISABLE TRIGGER Person.uAddress ON Person.Address;
update ....
ENABLE Trigger Person.uAddress ON Person.Address;

Use disable trigger statement and then do your update as below

DISABLE TRIGGER Person.uAddress ON Person.Address;
update ....
ENABLE Trigger Person.uAddress ON Person.Address;
緦唸λ蓇 2024-11-12 20:31:49

您应该更改表和触发器。可能的解决方案之一是向表中添加列,例如“触发”。当您进行“正常”更新时,您应该插入 1。如果您需要避免更新,则触发 = 0。触发代码应该是:

IF EXISTS(SELECT * FROM INSERTED WHERE triggered=1)
--here you trigger fired

You should change table and trigger. One of possible solutions is to add column to your table, eg Triggered. When you make "normal" update then you should insert 1. If you need to avoid update then triggered=0. Trigger code should be:

IF EXISTS(SELECT * FROM INSERTED WHERE triggered=1)
--here you trigger fired
太阳男子 2024-11-12 20:31:49

与Dalex的回答类似:

另一个解决方案是添加一列,例如Triggered。并在触发器中使用类似的东西。

IF NOT UPDATE(Triggered)
BEGIN
  RETURN;
END

UPDATE() 仅检查该列是否包含在触发器中,而不检查该值是否实际更改。如果您想要触发触发器的每个查询都有 Triggered = 1,它将触发。没有这个的查询将不会触发触发器。

您可以使用 nvarchar 列并使用原因字段作为标志和解释。

UPDATE Users
  SET Password = ..encrypted_password..,
      Reason = 'changed password'
WHERE UserID = ...

然后

IF NOT UPDATE(Reason)
BEGIN
  RETURN;
END

如果您在登录时更新 lastLogin 字段,您可能会排除原因,因此触发器不会触发。

UPDATE Users
  SET LastLogin = getDate()
WHERE UserID = ...

Similar to Dalex's answer:

Another solution is to add a column, like Triggered. And use something like this in your trigger.

IF NOT UPDATE(Triggered)
BEGIN
  RETURN;
END

UPDATE() merely checks to see if the column was included in the trigger, and not whether or not the value was actually changed. If every query you want to to fire the trigger has Triggered = 1, it will fire. Queries that don't have this will not fire the trigger.

You could use an nvarchar column and use a reason field as both a flag and an explanation.

UPDATE Users
  SET Password = ..encrypted_password..,
      Reason = 'changed password'
WHERE UserID = ...

and then

IF NOT UPDATE(Reason)
BEGIN
  RETURN;
END

Wheres if you update the lastLogin field upon login, you might might exclude reason, tus the trigger won't fire.

UPDATE Users
  SET LastLogin = getDate()
WHERE UserID = ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文