Sql Server在2个数据库之间触发

时间:2011-07-11 15:09:38

标签: triggers

我有2个数据库。其中一个名为Test,有一个名为Vehicles的表。另一个名为Test2的表有一个名为Clients的表。

当我在Test中的Vehicles表上插入新记录时,我需要更新Test2中Clients表上的NumVehicles字段。

这是否可以使用触发器?

2 个答案:

答案 0 :(得分:9)

你需要像

这样的东西
USE Test;
GO
CREATE TRIGGER afterVehicleInsert ON Vehicles AFTER INSERT
AS
BEGIN 
  IF @@rowcount = 0 RETURN;

  UPDATE Test2.[schema_name(default schema is dbo)].Clients 
  SET NumVehicles = NumVehicles +1 -- or whatever it should be
  FROM Test2.[schema_name(default schema is dbo)].Clients c
  INNER JOIN inserted i ON ([your join condition])
END;  
GO

更新当前表和另一个数据库中的表之间的唯一区别是您需要使用[db_name]引用“远程”表。[schema_name]。[table_name]

答案 1 :(得分:0)

这是工作代码,如下所示

USE BioStar;
    GO 
    CREATE TRIGGER trgAfterInsertnew ON [dbo].[TB_EVENT_LOG] 
    FOR INSERT
    AS
        declare @nDateTime int;
        declare @nReaderIdn int;
        declare @nEventIdn int;
        declare @nUserID int;
        declare @nIsLog smallint;
        declare @nTNAEvent smallint;
        declare @nIsUseTA smallint;
        declare @nType smallint;


        select @nDateTime=i.nDateTime from inserted i;  
        select @nDateTime=i.nReaderIdn from inserted i; 
        select @nEventIdn=i.nEventIdn from inserted i;  
        select @nUserID=i.nUserID from inserted i;

        select @nIsLog=i.nIsLog from inserted i;    
        select @nTNAEvent=i.nTNAEvent from inserted i;  
        select @nIsUseTA=i.nIsUseTA from inserted i;    
        select @nType=i.nType from inserted i;
        insert into [HRM].dbo.Device_Data
               (nDateTime,nReaderIdn,nEventIdn,nUserID,nIsLog,nTNAEvent,nIsUseTA,nType) 
        values(@nDateTime,@nDateTime,@nEventIdn,@nUserID,@nIsLog,@nTNAEvent,@nIsUseTA,@nType);


        --set @audit_action='Inserted Record -- After Insert Trigger.';
            PRINT 'AFTER DELETE TRIGGER fired.'
    GO