Sql Server Trigger between 2 databases

后端 未结 2 567
挽巷
挽巷 2020-12-09 13:50

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

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 14:29

    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]

提交回复
热议问题