Querying a different SQL Server instance - syntax

Pedro Soares 406 Reputation points
2022-04-26T09:16:56.047+00:00

Hi guys,

What is the query syntax to query a different SQL Server instance on the same server?

Imagine I have something like this:

Instance 1: SUBZERO\STAGING
Instance 2: SUBZERO\DWH

When I open a new query window, the connection is associated with one of the instances. How do I join database tables from both instances?

Thank you

Developer technologies Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Olaf Helper 47,436 Reputation points
    2022-04-26T10:16:17.867+00:00

    You can create "Linked Server" pointing to the other instance, then you can use a 4-part-qualifier to access the other SQL Server, like

    select * from servername.databasename.schema.tablename  
    

    See
    https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/linked-servers-database-engine?view=sql-server-ver15
    https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine?view=sql-server-ver15

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Pedro Soares 406 Reputation points
    2022-04-26T10:20:24.983+00:00

    Hi Olaf,

    Thank you, that makes sense. I tried that before I posted the question but it seems my user doesn't have permissions to add Linked Servers, so I couldn't test it properly.

    I'll mark it as Answer as soon as I can confirm :-)

    Best regards

    0 comments No comments

  2. Tom Phillips 17,771 Reputation points
    2022-04-26T15:29:31.24+00:00

    Just to be clear.

    SQL Server does not know the other instance exists. There is no difference between connecting to a different instance on different server and the same server. You need to use linked servers to connect to another instance.

    0 comments No comments

  3. Bert Zhou-msft 3,436 Reputation points
    2022-04-27T08:07:07.59+00:00

    Hi,@Pedro Soares

    Welcome to Microsoft T-SQL Q&A Forum!

    you should create a linked server first , and use the Server.Catalog.Schema.Table name to refer to tables in other instances . Use Inner join, like this:

    SELECT *  
    FROM server1_table t1  
    INNER JOIN server2.database.dbo.server1_table  as t2  
    ON t2.column=t1.column  
    

    Best regards,
    Bert Zhou


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.