Search code examples
sqlsql-serverjoinlinked-server

Joining Table via Linked Server


I have 2 servers with 2 different databases.

S1(Server) WITH DB1(Database) WITH T1(Table)

and

S2(Server) WITH DB2(Database) WITH T2(Table)

DB1 has a linked server to S2 DB2.

So i can run a query such as

SELECT * FROM T1 
JOIN [S2].[DB2].[T2] T2
ON T1.[ID] = T2.[ID]

And this runs correctly.

However, how can i run it in the opposite direction

e.g.

SELECT * FROM T2 
JOIN [S1].[DB1].[T1] T1
ON T2.[ID] = T1.[ID]

This errors with "Could not find server [S1].[DB1].[T1]"

Is there anyway i can join in this direction without having to create a linked server from S2 to S1?


Solution

  • This query:

    SELECT *
    FROM T2 JOIN
         [S1].[DB1].[T1] T1
         ON T2.[ID] = T1.[ID];
    

    Presumes that T2 is local. You can sort of do a hybrid:

    SELECT *
    FROM [S2].[DB2].[T2] T2 JOIN
         [DB1].[T1] T1
         ON T2.[ID] = T1.[ID];
    

    It is possible to link a server to itself, so if you did that, you could run this identical query on both servers:

    SELECT *
    FROM [S2].[DB2].[T2] T2 JOIN
         [S2].[DB1].[T1] T1
         ON T2.[ID] = T1.[ID];
    

    If you are trying to implement "equivalent" queries on two servers, then synonyms could help. You might be interested in the answers to this question.