日期:2014-05-18  浏览次数:20721 次

触发器递归问题,搞定马上结帐
Tfangwuinfo表:
CREATE   TRIGGER   [Tri_TFWinsert]   ON   [dbo].[Tfangwuinfo]  
FOR   INSERT
AS
begin
declare   @shouchu   bit   select   @shouchu=i.shouchu   from   inserted   i
if(@shouchu=1)
insert   Tyezhuinfo(yezhuID,yezhuname)   select   fangwuID,chanquanren   from   inserted   i
end

CREATE   TRIGGER   [Tri_TFWupdate]   ON   [dbo].[Tfangwuinfo]  
FOR   UPDATE
AS
begin
declare   @shouchu   bit   select   @shouchu=d.shouchu   from   deleted   d
if   (update(shouchu)   and   @shouchu=0)
insert   Tyezhuinfo(yezhuID,yezhuname)   select   fangwuID,chanquanren   from   inserted   i
if   update   (chanquanren)
update   Tyezhuinfo   set   yezhuname=i.chanquanren   from   inserted   i   where   Tyezhuinfo.yezhuID=i.fangwuID
end

Tyezhuinfo表:
CREATE   TRIGGER   [Tri_TYZinsert]   ON   [dbo].[Tyezhuinfo]  
FOR   INSERT
AS
begin
declare   @yezhuID   varchar(8)   select   @yezhuID=i.yezhuID   from   inserted   i  
declare   @name   varchar(10)   select   @name=i.yezhuname   from   inserted   i
declare   @IDcard   varchar(20)   select   @IDcard=i.IDcard   from   inserted   i
update   Tfangwuinfo   set   shouchu=1,chanquanren=i.yezhuname   from   inserted   i   where   Tfangwuinfo.fangwuID=i.yezhuID
insert   Trenkouinfo(yezhuID,name,sex,IDcard,chushendate,hunyinstate,YONyezhu)  
select   @yezhuID,@name, '男 ',@IDcard, '3000-1-1 ', '0 ', '1 '
end

T3表:Trenkouinfo
问题就是我在T1插入数据时可以触发插入T2但无法触发T2的触发器再插入T3,而我在T2插入时却可以.好象就是无法递归的问题.

另:Tri_TYZinsert中的insert   Trenkouinfo(yezhuID,name,sex,IDcard,chushendate,hunyinstate,YONyezhu)  
select   @yezhuID,@name, '男 ',@IDcard, '3000-1-1 ', '0 ', '1 '
这句有没好点的写法?传那么多参数觉得好烦琐

------解决方案--------------------
T3表:Trenkouinfo
问题就是我在T1插入数据时可以触发插入T2但无法触发T2的触发器再插入T3,而我在T2插入时却可以.好象就是无法递归的问题.
========我理解没有错啊,楼主有没有试过我上面的代码?

--1先执行下面语句
exec sp_configure 'nested triggers ',1 --这句是必须的
reconfigure
--2楼主只要改下面一个触发器就可以了

CREATE TRIGGER [Tri_TYZinsert] ON [dbo].[Tyezhuinfo]
FOR INSERT
AS
begin
declare @yezhuID varchar(8) select @yezhuID=i.yezhuID from inserted i
declare @name varchar(10) select @name=i.yezhuname from inserted i
declare @IDcard varchar(20) select @IDcard=i.IDcard from inserted i

alter table Tfangwuinfo DISABLE TRIGGER Tri_TFWupdate --新加的
update Tfangwuinfo set shouchu=1,chanquanren=i.yezhuname from inserted i where Tfangwuinfo.fangwuID=i.yezhuID
alter table Tfangwuinfo enable TRIGGER Tri_TFWupdate --新加的

insert Trenkouinfo(yezhuID,name,sex,IDcard,chushendate,hunyinstate,YONyezhu)
select @yezhuID,@name, '男 ',@IDcard, '3000-1-1 ', '0 ', '1 '
end