我有一个表 tbl1 ,其中有一列 tbl_names 。此列包含其他一些表的名称
现在我想用以下格式编写查询:
select * from (select tbl_names from tbl1)
我知道上面的查询不起作用,但我怎么能做到这一点?我是否需要编写存储过程或类似的东西并循环第二个查询的每个值并执行第一个查询?
由于
答案 0 :(得分:7)
您可以使用预准备陈述
SET @a = (select tbl_names from tbl1);
SET @x := CONCAT('SELECT * FROM ', @a);
Prepare stmt FROM @x;
Execute stmt;
DEALLOCATE PREPARE stmt;
干杯。
答案 1 :(得分:0)
您需要使用一些动态SQL。使用要执行的查询构建SQL字符串,然后调用exec(@sql)
完整示例:
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
答案 2 :(得分:-1)
只需在子查询中添加一个pseudonim:
select * from (select tbl_names from tbl1) a;
祝你好运)