SQL Server 触发器循环

SQL Server Trigger loop(SQL Server 触发器循环)
本文介绍了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 触发器循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)