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 th
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.
You'll need to use some dynamic SQL. Build up a SQL string with the query that you want to execute and then call exec(@sql)
Full example:
declare cur cursor for
select tbl_names from tbl1
declare @sql varchar(100), @tbl varchar(100)
open cur
fetch cur into @tbl
while @@FETCH_STATUS = 0 begin
set @sql = 'select * from ' + @tbl
exec(@sql)
fetch cur into @tbl
end
close cur
deallocate cur
Just add a pseudonim to the subquery:
select * from (select tbl_names from tbl1) a;
Good luck )