This is my situation. I have different tables, by example:
TABLE A
Name | Phone
John 123
Mick 233
TABLE B
Department | Position
IT xxx
HR yyy
And the next configuration table is created dynamically via web:
TABLE C
Source | Field
TABLE A Name
TABLE B Department
When I run the application, I read the Table C and I need to generate the data.
In this case, I need to list all the names from TABLE A and all the departments from TABLE B.
How can I query this? I hope somebody can help me.
Cheers!
If you have to do this in sql – which I would not recommend if you can not trust the content of TABLE C – then you will need to construct a variable that contains the sql query, then execute that sql query dynamically. How to do this will entirely depend on your DBMS. An example in MySQL (which assumes that TABLE C has only one row):
SQL Server syntax:
Since TABLE C will certainly have more than one row you will have to iterate through TABLE C. This can be done with a CURSOR, and again the exact details will be dependent on your DBMS.
Importantly, be aware that this is very dangerous if as you state TABLE C is created from the web. You have no guarantee what is in the FIELD and SOURCE fields: they could be filled with a sql injection attack by anyone with a little SQL knowledge. What you may need to do is safely validate that TABLE C’s contents are actual tables/columns via safely parameterized database meta-queries.