Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query across multiple databases on same server

Tags:

sql

sql-server

I am looking for a way of dealing with the following situation:

  1. We have a database server with multiple databases on it (all have the same schema, different data).

  2. We are looking for a way to query across all the databases (and for it to be easy to configure, as more databases may be added at any time). This data access must be realtime.

Say, as an example, you have an application that inserts orders - each application has its own DB etc. What we are then looking for is an efficient way for a single application to then access the order information in all the other databases in order to query it and subsequently action it.

My searches to date have not revealed very much, however I think I may just be missing the appropriate keywords in order to find the correct info...

like image 544
Paddy Avatar asked Dec 16 '13 12:12

Paddy


People also ask

Can you query across multiple databases?

In summary, if all your databases are on one server instance, then multiple database querying is as easy as prefixing the table name with the database or schema name depending on your database software. In other cases, you need to have one database with multiple schemas to make this technique work.

Can you query across databases?

With cross-database queries, you can seamlessly query data from any database in the cluster, regardless of which database you are connected to. Cross-database queries can eliminate data copies and simplify your data organization to support multiple business groups on the same cluster.


1 Answers

You must specify the database name before any database object.

Single database:

SELECT * FROM [dbo].[myTable] 

Multiple dabases:

SELECT * FROM [DB01].[dbo].[myTable] UNION ALL SELECT * FROM [DB02].[dbo].[myTable] UNION ALL SELECT * FROM [DB03].[dbo].[myTable] 
like image 113
TcKs Avatar answered Sep 19 '22 15:09

TcKs