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?
union allbetween theselectstatements, thenexecutethat string? That would return a single result set.insertthe results of eachexecuteinto a (temporary) table: Select INTO Temp table from dynamic sql string variable.