SQL Server Trigger loop(SQL Server 触发器循环)
问题描述
我想知道是否可以在两个表上添加一个触发器,将数据复制到另一个表.
I would like to know if there is anyway I can add a trigger on two tables that will replicate the data to the other.
例如:
我有两个用户表,users_V1 和 users_V2,当用户使用其中一个 V1 应用程序更新时,它也会激活一个触发器,更新它在 users_V2 中.
I have a two users tables, users_V1 and users_V2, When a user is updated with one of the V1 app, it activate a trigger updating it in users_V2 as well.
如果我想在V2表上添加相同的触发器,以便在V2中更新用户时更新V1中的数据,是否会进入无限循环?有什么办法可以避免这种情况.
If I want to add the same trigger on the V2 table in order to update the data in V1 when a user is updated in V2, will it go into an infinite loop? Is there any way to avoid that.
推荐答案
我不建议在处理过程中明确禁用触发器 - 这会导致奇怪的副作用.
I don't recommend explicitly disabling the trigger during processing - this can cause strange side-effects.
检测(和防止)触发器中循环的最可靠方法是使用 CONTEXT_INFO().
The most reliable way to detect (and prevent) cycles in a trigger is to use CONTEXT_INFO().
示例:
CREATE TRIGGER tr_Table1_Update
ON Table1
FOR UPDATE AS
DECLARE @ctx VARBINARY(128)
SELECT @ctx = CONTEXT_INFO()
IF @ctx = 0xFF
RETURN
SET @ctx = 0xFF
-- Trigger logic goes here
查看此链接以获得更详细的示例.
See this link for a more detailed example.
SQL Server 2000 中 CONTEXT_INFO() 的注意事项:
Note on CONTEXT_INFO() in SQL Server 2000:
支持上下文信息,但显然不支持 CONTEXT_INFO 函数.你必须改用这个:
Context info is supported but apparently the CONTEXT_INFO function is not. You have to use this instead:
SELECT @ctx = context_info
FROM master.dbo.sysprocesses
WHERE spid = @@SPID
这篇关于SQL Server 触发器循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 触发器循环
基础教程推荐
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
