0

I have a table which contains a employee ID and a database ID code in database DBX0 table 'FirstTable':

Employee ID Database ID
123 1
456 2
789 2
149 3

The database name is stored in a different table 'databases' like :

Database ID DB name
1 DBX1
2 DBX2
3 DBX3

So what I'm trying to do is join the first table with a separate table which is stored in the identified database, like

SELECT * from DBX0.dbo.FirstTable a join (SELECT [DB name] from DBX0.dbo.databases where [database ID] = a.[database ID]).dbo.OtherTable

(I don't think this will actually work with a subquery, but this would return the result that I want in theory.)

I have tried dynamic sql with a cursor to iterate through each database and then only return results based on database ID = database ID and Employee ID = Employee ID, but this returns the results in a separate result per database.

Also tried:

Select * from (SELECT * from DBX0.dbo.FirstTable a join '+@dbname+'.dbo.OtherTable on a.employeeid = b.employeeid and a.dbid = b.dbid)

in dynamic sql, but this didn't work either.

Is there any way to get all of the data in one result?

3
  • Can you combine all of the dynamic SQL queries into one big query string with union all between the select statements, then execute that string? That would return a single result set. Commented Mar 17, 2021 at 2:07
  • There are a lot of databases that exist so doing that would be too resource intensive I think. Commented Mar 17, 2021 at 13:59
  • You can insert the results of each execute into a (temporary) table: Select INTO Temp table from dynamic sql string variable. Commented Mar 17, 2021 at 14:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.