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

时间:2012-12-13 04:59:54

标签: mysql select prepared-statement

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

declare str varchar(2000);
set @str="select 
       from
        `cdr` ";
 PREPARE stmt1 FROM @str;
  EXECUTE stmt1;

现在我想执行像这样的查询

 select * from stmt1;

1 个答案:

答案 0 :(得分:3)

编辑:请尝试以下代码:

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;

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

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

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

SELECT * FROM tempTable;