如何在mysql中执行String然后插入到临时表中?

Mas*_*oud 5 mysql select prepared-statement

我想将动态查询的结果插入临时表或将此结果用作表的方法。例如 :

declare str varchar(2000);
set @str="select 
       from
        `cdr` ";
 PREPARE stmt1 FROM @str;
  EXECUTE stmt1;
Run Code Online (Sandbox Code Playgroud)

现在我想执行这样的查询

 select * from stmt1;
Run Code Online (Sandbox Code Playgroud)

Sah*_*hah 4

编辑:尝试下面的代码:

DECLARE str VARCHAR(2000);
SET @str="CREATE TEMPORARY TABLE tempTable1 select * from `cdr` ";
PREPARE stmt1 FROM @str;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

SELECT * FROM tempTable1;
-- Code what you want to work on temptable1 
DROP TABLE tempTable1;
Run Code Online (Sandbox Code Playgroud)

原始答案:首先创建临时表,然后使用以下代码:

DECLARE str VARCHAR(2000);
SET @str="insert into tempTable select * from `cdr` ";
PREPARE stmt1 FROM @str;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样执行查询:

SELECT * FROM tempTable;
Run Code Online (Sandbox Code Playgroud)