0

I have following arrangement of tables (tableX and tableY) are in similar pattern. And when i mean {object.table} I would like to have the real table there instead of a string. What now I do is I execute the following SQL for each entry in Object table. But I would like to know is there any SQL solution where I can do this is a single query.

SELECT
    persons.person_id AS "person_id",
    {object.table}.avl AS "available",
    "{object.variable_name}" AS "variable_name",
FROM
    persons
INNER JOIN {object.table} ON {object.table}.person_id = persons.person_id
WHERE
    {object.table}.{object.column} = {object.code};

Object
- table (tableX, tableY)
- column
- code
- variable_name

tableX
- person_id
- more_info

persons
- person_id
3
  • Maybe you can simply do this with a UNION, perhaps you want the MySQL variant of EXECUTE IMMEDIATE: dev.mysql.com/doc/refman/5.1/en/…, but I really couldn't tell, since I don't understand at all what it is you're trying to do. Commented May 19, 2014 at 19:48
  • My table "Object" contains two strings which are table and column. This conatains a name of a table in the database and name of a coumn in that table. I need to use them together and get the outcome. But Since its kind of dynamic data I dont know how to use it in MySql Commented May 19, 2014 at 19:52
  • 1
    You should be able to do it with what they call prepared statements in MySQL. Check out this answer: stackoverflow.com/a/10480456/2947592 Commented May 19, 2014 at 20:47

1 Answer 1

1

You are trying to use table name and column name as parameter in your query; that's not possible. Table names and column names can't be dynamic in a SQL query.

But it can be achievable programmatically using PREPARED query and a nice example is just given here with code sample Can I use a dynamic table name in stored procedure

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.