4

I have 2 databases. One, named Test, has a table named Vehicles. Another, named Test2 has a table named Clients.

When I insert a new record on the Vehicles table in Test, I need to update the NumVehicles field on the Clients table in Test2.

Is this possible using triggers?

2 Answers 2

12

You need something like

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

The only difference between updating the table in current and another db is that you need to refer a "remote" table using [db_name].[schema_name].[table_name]

Sign up to request clarification or add additional context in comments.

Comments

0

This is working code is given below

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.