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


当前回答

sp_addlinkedserver('servername')

所以它应该是这样的

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

其他回答

我在连接SQL_server 2008到远程服务器上托管的SQL_server 2016时遇到了同样的问题。其他的答案对我来说并不直接。我把我的调整解决方案写在这里,因为我认为它可能对其他人有用。

远程IP db连接的扩展答案:

步骤1:连接服务器

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';
   
EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...其中SRV_NAME是一个虚构的名称。我们将使用它从查询中引用远程服务器。aaa.bbb.ccc.ddd是SQLserver DB的远程服务器的ip地址。

步骤2:运行查询 例如:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...就是这样!

语法详细信息:sp_addlinkedserver和sp_addlinkedsrvlogin

sp_addlinkedserver('servername')

所以它应该是这样的

select * from table1
unionall
select * from [server1].[database].[dbo].[table1]
 select * 
 from [ServerName(IP)].[DatabaseName].[dbo].[TableName]

跨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

试试这个:

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