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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With