如何从SQL Server中两个不同服务器上的两个不同数据库中选择同一查询中的数据?


当前回答

sp_addlinkedserver('servername')

所以它应该是这样的

select * from table1
unionall
select * from [server1].[database].[dbo].[table1]

其他回答

sp_addlinkedserver('servername')

所以它应该是这样的

select * from table1
unionall
select * from [server1].[database].[dbo].[table1]

跨2个不同的数据库进行查询是一种分布式查询。以下是一些技巧及其优缺点:

Linked servers: Provide access to a wider variety of data sources than SQL Server replication provides Linked servers: Connect with data sources that replication does not support or which require ad hoc access Linked servers: Perform better than OPENDATASOURCE or OPENROWSET OPENDATASOURCE and OPENROWSET functions: Convenient for retrieving data from data sources on an ad hoc basis. OPENROWSET has BULK facilities as well that may/may not require a format file which might be fiddley OPENQUERY: Doesn't support variables All are T-SQL solutions. Relatively easy to implement and set up All are dependent on connection between source and destionation which might affect performance and scalability

我知道这是一个老问题,但我使用同义词。假设查询在数据库服务器A中执行,并在数据库服务器B中查找服务器A上不存在的表,然后在数据库中添加从服务器B调用您的表的同义词。您的查询不需要包括任何模式,或不同的数据库名称,只需按惯例调用表名,它就可以工作。

没有必要链接服务器,因为同义词是说,某种链接。

SELECT
        *
FROM
        [SERVER2NAME].[THEDB].[THEOWNER].[THETABLE]

您还可以使用链接服务器。链接服务器也可以是其他类型的数据源,比如DB2平台。这是一种尝试从SQL Server TSQL或Sproc调用访问DB2的方法…

试试这个:

SELECT * FROM OPENROWSET('SQLNCLI', 'Server=YOUR SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
UNION
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=ANOTHER SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a