I have two tables. One table contains information on where to find information in another table.
Table A:
PK | ManagerKey | Table | ColumnOne | ColumnTwo |
---|---|---|---|---|
51 | 101 | DataBase1.dbo.Table1 | TestingColumn1 | TestingColumn5 |
29 | 201 | DataBase1.dbo.Table6 | StagingColumn3 | StagingColumn4 |
37 | 301 | DataBase1.dbo.Table3 | ProductionColumn4 | ProductionColumn9 |
DataBase1.dbo.Table1 (Each of the three tables have the same structure, but I will only be using DataBase1.dbo.Table1 in this example):
PK | TestingColumn1 | TestingColumn2 | TestingColumn3 | TestingColumn4 | TestingColumn5 |
---|---|---|---|---|---|
565 | $156 | $870 | StringOne | StringTwo | StringThree |
876 | $250 | $840 | StringOne | StringTwo | StringThree |
151 | $165 | $950 | StringOne | StringTwo | StringThree |
If I narrow down the results of Table A to a single row, how can I use the row results in ColumnOne and ColumnTwo of Table A to return the desired columns of the second table? The database listed in the Table column of Table A will always be the same (DataBase1). However, the table names are different, as shown in the example.
Expected results:
PK | TestingColumn1 | TestingColumn5 |
---|---|---|
565 | $156 | StringThree |
876 | $250 | StringThree |
151 | $165 | StringThree |
Any help is appreciated. Thank you.
CodePudding user response:
You would need to dynamically build the SQL to execute - I would have honestly thought how to do this would have been established before implementing this design!
There's no real need to have this clunky requirement for dynamic SQL, this could all be contained in a single configuration table.
Something like:
declare @sql nvarchar(max);
select @sql = Concat('select ', QuoteName(columnone), ', ', QuoteName(columntwo), ' from ', [table])
from A
where pk=51;
exec (@sql);
I would suggest that naming a column "Table" be avoided since it's a reserved word and the contents is not a table but a fully qualifed object name.