Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query dynamic table name in FOR

I have a table tbl1 which has a column tbl_names. This column contains the name of some other tables.
Now I want to write a query in the following format:
select * from (select tbl_names from tbl1)

I know that the query above will not work but how I can achieve this? Do I need to write a stored procedure or something like that and loop on each value of second query and execute first query?

Thanks

like image 262
Sibtain Norain Avatar asked Oct 22 '13 06:10

Sibtain Norain


People also ask

How do I run a dynamic query in SQL?

To run a dynamic SQL statement, run the stored procedure sp_executesql as shown below : EXEC sp_executesql N'SELECT statement'; Use prefix N with the sp_executesql to use dynamic SQL as a Unicode string.

Can I use CTE in dynamic SQL?

They allow to encapsulate the SQL query and reuse result recursively as a data source in the main query or in another CTE within one statement. In this article I'll illustrate how to use CTEs using an example of dynamic query which counts records from one table joined with second table used to limit the result set.


1 Answers

You can use prepared statements

SET @a = (select tbl_names from tbl1);
SET @x := CONCAT('SELECT * FROM ', @a);
Prepare stmt FROM @x;
Execute stmt;
DEALLOCATE PREPARE stmt;

PREPARE Syntax

Cheers.

like image 55
Carlos González Avatar answered Sep 28 '22 09:09

Carlos González