1

Is there a way to execute union of 2 SQL queries from different SQL Servers as shown below in my query?

Select * from table1 (server 1)
union
Select * from table1 (server 2)
Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
Hamza Lahbabi
  • 29
  • 1
  • 9
  • Look into linked servers. – Steven Lemmens Jan 14 '20 at 10:10
  • 1
    Really, you should have [searched SO](https://stackoverflow.com/search?q=sql+server+linked+server) about this in the first instance. – Paul Jan 14 '20 at 10:19
  • Paul, I didn't know about linked server. So I think that your comment is no needed and unnecessary. – Hamza Lahbabi Jan 14 '20 at 10:50
  • Well, in that case I searched on what you specified: [SQL queries from different SQL Servers](https://stackoverflow.com/search?q=SQL+queries+from+different+SQL+Servers). Searching SO is a basic function of the site. – Paul Jan 14 '20 at 13:59

2 Answers2

4

You need to create the linked server so you have to access of that server after that You can try this way to call and execute the query.

A linked server allows for access to distributed, heterogeneous queries against OLE DB data sources. After a linked server is created, distributed queries can be run against this server, and queries can join tables from more than one data source. If the linked server is defined as an instance of SQL Server, remote stored procedures can be executed.

Select * from <ServerName>.<databaseName>.<SchemaName>.<Table1>

Here is the official documentation to configure the link server.

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
  • 1
    Add a link to the documentation (https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine?view=sql-server-ver15). – Paul Jan 14 '20 at 10:15
1

Look into linked servers first.

Then write your query with aliases, like this:

SELECT r.[Project_ID], a.[Name] FROM [LocalDatabase].[dbo].[Record] r inner join [LinkedServer].[Reporting].[dbo].[Active] a ON r.[Project_ID] = a.[Delivery_Number];

Steven Lemmens
  • 690
  • 5
  • 13