Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Trigger loop

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.

For example:

  • 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.

  • 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.

like image 280
Roch Avatar asked Feb 10 '10 14:02

Roch


2 Answers

I don't recommend explicitly disabling the trigger during processing - this can cause strange side-effects.

The most reliable way to detect (and prevent) cycles in a trigger is to use CONTEXT_INFO().

Example:

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.


Note on CONTEXT_INFO() in SQL Server 2000:

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
like image 192
Aaronaught Avatar answered Oct 12 '22 07:10

Aaronaught


  • Either use TRIGGER_NESTLEVEL() to restrict trigger recursion, or

  • check the target table whether an UPDATE is necessary at all:

    IF (SELECT COUNT(1) 
    FROM users_V1 
    INNER JOIN inserted ON users_V1.ID = inserted.ID
    WHERE users_V1.field1 <> inserted.field1
    OR users_V1.field2 <> inserted.field2) > 0 BEGIN
    
    UPDATE users_V1 SET ...
    
like image 39
devio Avatar answered Oct 12 '22 07:10

devio