How can I select data in the same query from two different databases that are on two different servers in SQL Server?
Querying across 2 different databases is a distributed query. Here is a list of some techniques plus the pros and cons:
sp_addlinkedserver('servername')
so its should go like this -
select * from table1
unionall
select * from [server1].[database].[dbo].[table1]
select *
from [ServerName(IP)].[DatabaseName].[dbo].[TableName]
try this:
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
Simplified solution for adding linked servers
First server
EXEC sp_addlinkedserver @server='ip,port\instancename'
Second Login
EXEC sp_addlinkedsrvlogin 'ip,port\instancename', 'false', NULL, 'remote_db_loginname', 'remote_db_pass'
Execute queries from linked to local db
INSERT INTO Tbl (Col1, Col2, Col3)
SELECT Col1, Col2, Col3
FROM [ip,port\instancename].[linkedDBName].[linkedTblSchema].[linkedTblName]
Server Objects---> linked server ---> new linked server
In linked server write server name or IP address for other server and choose SQL Server In Security select (be made using this security context ) Write login and password for other server
Now connected then use
Select * from [server name or ip addresses ].databasename.dbo.tblname