0

Is it possible to connect two tables from different databases on the same SQL Server 2008 R2 instance? When one is being updated or inserted into, the other table should be updated automatically.

Example:

  • Table 1 from Customer database
  • Table 2 from Supplier database

When something is inserted into Table 1, at the same time Table 2 should be updated with same data of Table 1.

TT.
  • 15,774
  • 6
  • 47
  • 88

2 Answers2

2

One way is to create a SYNONYM for Customer.dbo.Table1 in the Supplier database. You can then query the synonym as though it were in the Supplier database.

Suppose you have the Customer database with Table1 and the Supplier database with Table2. Suppose both tables are in the dbo schema. You can then test the following in SQL Server Management Studio (SSMS):

USE Supplier; -- Tell SSMS to switch to the Supplier database

CREATE SYNONYM Table1 FOR Customer.dbo.Table1; -- this creates a synonym permanently in the Supplier database; you only need to execute this once

SELECT * FROM Table1; -- select all from Customer.dbo.Table1, from within the context of database Supplier

This way there is no need for TRIGGERs and the corresponding overhead (you would need 3 TRIGGERs to keep the tables in sync).

TT.
  • 15,774
  • 6
  • 47
  • 88
0
USE Customer
GO

CREATE TRIGGER dbo.Table1_AI
   ON dbo.Table1
   AFTER INSERT
AS 
BEGIN
    IF (@@ROWCOUNT = 0)
        RETURN;

    SET NOCOUNT ON;

    UPDATE t2
        SET ColumnX = i.ColumnX, ColumnY = i.ColumnY
        FROM Supplier.dbo.Table2 t2
        INNER JOIN inserted i on i.id = t2.id;
END
GO

Replace ColumnX = i.ColumnX, ColumnY = i.ColumnY and i.id = t2.id considering your logic.

Ruslan K.
  • 1,912
  • 1
  • 15
  • 18