I have a Users
table,
╔════╦══════════════╗
║ Id ║ Name ║ Db ║
╠════╬══════════════╣
║ 1 ║ Peter ║ DB1 ║
║ 2 ║ John ║ DB16 ║
║ 3 ║ Alex ║ DB23 ║
╚════╩══════════════╝
and many databases with the same structure (the same tables, the same procedures, etc.), so each database has a table called Project
, and this is the structure of the Project
table,
╔════╦════════╦═════════════╗
║ Id ║ Request ║ Information ║
╠════╬════════╬═════════════╣
║ 1 ║ 126 ║ XB1 ║
║ 2 ║ 126 ║ D6 ║
║ 3 ║ 202 ║ BM-23 ║
╚════╩════════╩═════════════╝
So, when I query the database:
SELECT count(distinct([Request])) as nbrRequests FROM [SRV02].[DB1].[dbo].[Project]
I get this result:
╔═════════════╗
║ NbrRequests ║
╠═════════════╣
║ 2 ║
╚═════════════╝
Now I want to "bind" / "join" ... the results from the Users
table to this query, where the Db
column in the Users
table is the name of my database, so I can get this result:
╔════╦══════════════╦════════════╗
║ Id ║ Name ║ Db ║ NbrRequests ║
╠════╬══════════════╬════════════╣
║ 1 ║ Peter ║ DB1 ║ 2 ║
║ 2 ║ John ║ DB16 ║ 3 ║
║ 3 ║ Alex ║ DB23 ║ 6 ║
╚════╩══════════════╩════════════╝
I am trying to use dynamic SQL but no luck.
NB: Each user has only one database, and the database belongs to only one user, this is a one-to-one relationship
source share