I have to join queries from multiple databases, something like:
SELECT T1.*, T2.* FROM DatabaseA.dbo.Table1 AS T1
INNER JOIN DatabaseB.dbo.Table2 AS T2 ON T1.ID = T2.ID
My questions:
- How should I setup the connection string of
System.Data.SqlClient.SqlConnection? Should I omit or leave empty theInitial Catalog? Should I set it toDatabaseA? - Is this a good way to perform this task? I’m thinking to prepare a third DB without tables but with a view with that
SELECT(I can’t put a view in the existing databases). Query usually is executed in 10/15 seconds but user has to wait so even few seconds less will be appreciated.
All DBs share the same login credentials.
This depends on the login within your connection string more than the
Initial Catalog.You can specify either database in your connection string, as long as the login that you’re using has the permission required to query from both tables in both databases.
There’s nothing inherently wrong with a query that spans multiple databases, so your proposed solution looks good to me.
Just be aware that if you’re the one designing these databases, and determining which tables should live in which databases, that there is no referential integrity across databases, so ideally any tables that relate to each other should live in a single database.