Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute String in mysql and then insert into temp table?

I want to insert the results from a dynamic query into a temp table or a way to use this result as a table. for example :

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

and now i want to execute a query like this

 select * from stmt1;
like image 561
Masoud Avatar asked Oct 06 '22 16:10

Masoud


1 Answers

EDIT: Try below Code:

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;

Orginal Answer: First Create Temp Table and then use below code:

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

Then you can execute query like this:

SELECT * FROM tempTable;
like image 118
Saharsh Shah Avatar answered Oct 10 '22 03:10

Saharsh Shah