Queries in the same window for multiple databases, servers, and tables

Jonathan Brotto 420 Reputation points
2024-09-16T13:02:52.5733333+00:00

I was wondering in SSMS in the query window could I write multiple queries that use different servers, databases, and tables?

A compounded question and answer I am expecting for this.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,976 questions
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
39,671 questions
SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
101 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,652 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 66,461 Reputation points
    2024-09-16T17:50:51.3+00:00

    because SSMS supports the go command, you can use different batches to query different database without having to include the database name in the query (no help for linked servers).

    use database1
    go
    
    select * from table1
    go
    
    use database2
    go
    
    select * from table2
    go
    
    
    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Olaf Helper 45,096 Reputation points
    2024-09-16T16:16:45.4133333+00:00

    You can use 3-part qualifier to access different databases on the same SQL Server like

    SELECT * FROM Database.Schema.Table
    

    and "Linked Server" to access different SQL Server, see

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

    1 person found this answer helpful.
    0 comments No comments

  2. Erland Sommarskog 112.7K Reputation points MVP
    2024-09-16T21:45:55.07+00:00

    If you want to query multiple servers there is one option that is a little on the advanced side. In SSMS, find Registered Servers in the View menu. In this window you can define groups of servers. You can then right-click a group and select New Query. SSMS will now run your queries in all servers in the server group. You get the server name in an extra column in the result set.

    1 person found this answer helpful.
    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.