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

相关文章