Execute a query from a SPECIFIC Server/DB

Dom 751 Reputation points

I will often be working with queries with multiple servers and databases open in SSMS at the same time. When I run a query, I know I can use [DATABASE] to run in a specific, but SS seems to get confused about which SERVER I want to run on. I'm logged into several different servers in SSMS (all with different credentials). How can I FORCE my query to execute ON SERVER-A using DB-B?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,607 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 54,626 Reputation points

    query windows are tied to server connection. you can change the database (use database) from the drop down. to change the connection, in the query window right click and pick:

    connection->change connection

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. CosmogHong-MSFT 22,541 Reputation points Microsoft Vendor

    Hi @Dom

    You could go to SQLCMD mode in an SSMS query Window (menu bar Query-->SQLCMD mode) using SQL command :CONNECT to connect other server and USE to specify database.

    User's image

    Check this example:

    :CONNECT Server1  
    Use Database_A  
    Select * from Table1
    :CONNECT Server2  
    Use Database_B  
    Select * from Table2 
    :CONNECT Server3  
    Use Database_C  
    Select * from Table3 

    Note that the query window connection reverts back to the initial connection after each GO.

    Best regards,

    Cosmog Hong

    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.

    1 person found this answer helpful.
    0 comments No comments