I have a small table tbl_a that is something like
id | fieldName | tableName |
---|---|---|
1 | field1 | tbl_1 |
2 | field2 | tbl_1 |
3 | field3 | tbl_2 |
and I want to be able to come up with a function or proc or something where I can specify the fieldId from tbl_a and then query the correct field and table from that. something like
select * from my_function(3)
should end up being equivalent to
select field3 from tbl_2
I've been looking into dynamic sql and user functions but can't seem to figure out how to feed the results of the query into another.
EDIT:
As @Larnu correctly surmised, there is a larger task hiding behind the one posed in the original question. The premise is this:
- tblArchive stores the values of certain "static" fields (found in other tables) with a Date attached. If/when these fields are changed in their original table, then a record is inserted into tblArchive. More-or-less an audit table.
eg: in tbl_accounts, AdjustmentFactor field (fieldId=3) for accountId=1 changes from 1.0 to 0.5 on '2022-06-10'.
Insert into tblArchive (fieldId, accountId, date, value) values (3,1,'2022-06-10',0.5)
- tblArchive was only created in 2019. I've been tasked with back-filling records from 2017 on. That is, to insert records that would have been inserted had tblArchive existed in 2017.
- In order to backfill, I have to look into the real audit tables (for previous example this would be tblAccountsAudit for that particular fieldId).
- The fields of interest and their respective tables are given in tblFields. tblFields would be tbl_a from the original question and for the example given we'd have something like
id | fieldName | tableName |
---|---|---|
3 | AdjustmentFactor | tbl_accounts |
Assume also that the design is what it is and I have no power to overhaul the design/structure of the database.