通过连接不同服务器上两个数据库中的两个表来查询数据

在不同服务器上的两个不同数据库中有两个表,我需要加入它们以进行少量查询.我有哪些选择?我该怎么办?

There are two tables in two different databases on different servers, I need to join them so as to make few queries. What options do I have? What should I do?

推荐答案

您需要使用 sp_addlinkedserver 来创建服务器链接.有关用法,请参阅参考文档.建立服务器链接后,您将像往常一样构造查询,只需在数据库名称前加上另一台服务器即可.即:

You'll need to use sp_addlinkedserver to create a server link. See the reference documentation for usage. Once the server link is established, you'll construct the query as normal, just prefixing the database name with the other server. I.E:

-- FROM DB1
SELECT *
FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
    INNER JOIN [DB2].[MyDatabaseOnDB2].[dbo].[MyOtherTable] tab2
        ON tab1.ID = tab2.ID

一旦建立了链接,您还可以使用OPENQUERY 在远程服务器上执行 SQL 语句并只将数据传回给您.这可能会快一点,它会让远程服务器优化您的查询.如果您在上面的示例中将数据缓存在 DB1 上的临时(或内存中)表中,那么您将能够像连接标准表一样查询它.例如:

Once the link is established, you can also use OPENQUERY to execute a SQL statement on the remote server and transfer only the data back to you. This can be a bit faster, and it will let the remote server optimize your query. If you cache the data in a temporary (or in-memory) table on DB1 in the example above, then you'll be able to query it just like joining a standard table. For example:

-- Fetch data from the other database server
SELECT *
INTO #myTempTable
FROM OPENQUERY([DB2], 'SELECT * FROM [MyDatabaseOnDB2].[dbo].[MyOtherTable]')

-- Now I can join my temp table to see the data
SELECT * FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
    INNER JOIN #myTempTable tab2 ON tab1.ID = tab2.ID

查看关于 OPENQUERY 的文档 以查看更多示例.上面的例子非常做作.在这个特定示例中,我肯定会使用第一种方法,但是如果您使用查询过滤掉一些数据,使用 OPENQUERY 的第二个选项可以节省一些时间和性能.

Check out the documentation for OPENQUERY to see some more examples. The example above is pretty contrived. I would definitely use the first method in this specific example, but the second option using OPENQUERY can save some time and performance if you use the query to filter out some data.

相关文章