简体   繁体   English

通过链接服务器连接表

[英]Joining Table via Linked Server

I have 2 servers with 2 different databases. 我有2个服务器和2个不同的数据库。

S1(Server) WITH DB1(Database) WITH T1(Table) S1(服务器)和DB1(数据库)和T1(表)

and

S2(Server) WITH DB2(Database) WITH T2(Table) S2(服务器)和DB2(数据库)和T2(表)

DB1 has a linked server to S2 DB2. DB1具有到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 但是,我如何以相反的方向运行它

eg 例如

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

This errors with "Could not find server [S1].[DB1].[T1]" 出现以下错误: “找不到服务器[S1]。[DB1]。[T1]”

Is there anyway i can join in this direction without having to create a linked server from S2 to S1? 无论如何,我可以朝这个方向加入而不必创建从S2到S1的链接服务器?

This query: 该查询:

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

Presumes that T2 is local. 假定T2是本地的。 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. 您可能对此问题的答案感兴趣。

Gordon's answer is more thorough but you can rewrite your second query as: 戈登的答案更为详尽,但您可以将第二个查询重写为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM