简体   繁体   English

SQL Server 2008中的递归触发器

[英]Recursive Triggers in SQL Server 2008

I have two tables table1 and table2 , table2 have hierarchical data like below 我有两个表table1table2table2有分层数据,如下所示

  geo_id     parent_id
        1       NULL      
        2        1        
        3        2        
        4        3        
        5        3        
        6        3   

and table1 has data like below 和table1有如下数据

ID    geo_id
1       2      
2       3        
3       3        
4       3        
5       5       
6       5  

finally I have below Update trigger, 最后我有更新触发器,

USE [MyDB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[updateGeoHierarchyChilds] ON [dbo].[table2]
FOR UPDATE
AS
declare @ID int
BEGIN

 Declare VicIds CURSOR LOCAL FOR  SELECT geo_id from inserted
 OPEN VicIds
 FETCH NEXT  FROM VicIds into @ID
 WHILE @@FETCH_STATUS=0
 BEGIN
 update table1
set anyCol=AnyValue // suppose setting any column
where geo_id=@ID
update table2
set anyCol=AnyValue // suppose setting any column
where parent_id=@ID


FETCH NEXT FROM VicIds INTO @ID
    END
 CLOSE VicIds
 DEALLOCATE VicIds
END

when I update table2 for example, I run below command stand alone 例如,当我更新table2时,我在命令站下单独运行

update table2
set anyCol=anyValue //this line is supposition for sake of example
where geo_id=2

it updates table1 for geo_id=2 it also updates all child where parent_id=2 in table2 but it not updating table1 against childs of geo_id=2 simply saying, When below portion of trigger called 它更新了table1 for geo_id=2它还更新了table2parent_id=2所有子geo_id=2 ,但它没有更新table1geo_id=2的子geo_id=2只是说,当调用下面的触发器部分时

update table2
set anyCol=AnyValue // suppose setting any column
where parent_id=@ID

it updates bunch of child records in same table, but child records not updating thier relation records in table1 它更新了同一个表中的一堆子记录,但子记录没有更新table1的关系记录

You trigger will not recurse till you set an option 在设置选项之前,触发器不会递归

ALTER DATABASE [you db] SET RECURSIVE_TRIGGERS ON WITH NO_WAIT
GO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM