MySql:如何使用动态select语句创建临时表?

时间:2014-09-02 08:05:15

标签: mysql sql stored-procedures temp-tables

正如您从标题中可以理解的那样,我想通过使用动态select语句来创建临时表。这是我的代码:

 declare  strwhere varchar(30);
if hour(now()) >= 16 and minute(now()) >=30 then
    set strwhere = ' day(now()) +1 ';
else 
    set strwhere = '  day(now()) ';
end if;
set @query = concat("select  pc.customerid,
                    deliverytimespanid,
                    pc.id,
                    ca.districtid,
                    pc.status,
                    pc.orderid,
                    deliverydatetime
                from packages as pc
                inner join  customeraddresses as ca on ca.id = pc.addressid
                where pc.status = 1
                and day(pc.deliverydatetime) =",strwhere,"
                and month(pc.deliverydatetime) = month(now()) 
                and year(pc.deliverydatetime) = year(now()) ");

prepare resultset from @query;
execute resultset;
deallocate prepare resultset;
create temporary table if not exists table2 as (select * from resultset);

返回

  

结果集不存在。

我该如何选择结果?

1 个答案:

答案 0 :(得分:6)

使用SELECT语句创建表。您也可以缩短WHERE条款。

declare  strwhere varchar(30);
if hour(now()) >= 16 and minute(now()) >=30 then
    set strwhere = ' CURDATE() + INTERVAL 1 DAY ';
else 
    set strwhere = '  CURDATE() ';
end if;
set @query = concat("CREATE TEMPORARY TABLE table2 AS
                    SELECT  pc.customerid,
                    deliverytimespanid,
                    pc.id,
                    ca.districtid,
                    pc.status,
                    pc.orderid,
                    deliverydatetime
                from packages as pc
                inner join  customeraddresses as ca on ca.id = pc.addressid
                where pc.status = 1
                and pc.deliverydatetime =",strwhere,"
                );

prepare resultset from @query;
execute resultset;
deallocate prepare resultset;