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
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01