Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server Trigger between 2 databases

Tags:

triggers

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?

like image 645
Amr Elnashar Avatar asked Dec 28 '22 17:12

Amr Elnashar


1 Answers

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]

like image 115
a1ex07 Avatar answered Jan 20 '23 15:01

a1ex07