简体   繁体   中英

Creating temporary table inside stored procedure

I am working on writing my first stored procedure for MySQL.

The stored procedure needs to create a temporary table and then insert some data into it.

If I manually create a normal table, outside of the stored proc, so the stored proc isn't creating the temporary table the stored proc is created and does exactly what I'm after.

If I then add the create temporary table to the stored proc instead, MySQL workbench then shows unexpected end and the en of the create statement.

Below is my stored proc

    DELIMITER //
    CREATE PROCEDURE getLast24Hours()
    BEGIN
#End of the below line I get unexpected end without this it works fine
        CREATE TABLE hours (`Hour` VARCHAR(8) NOT NULL, `Value` INT NOT NULL DEFAULT 0, PRIMARY KEY(`Hour`)); 

        DECLARE crt_time VARCHAR(8);
        DECLARE counter INT;
        DECLARE currentTime DATETIME;

        SET currentTime = NOW();

        SET crt_time = DATE_FORMAT(currentTime, '%d-%m %H');
        SET counter = 0;
        WHILE counter < 23 DO
            INSERT INTO hours (`Hour`) VALUES (crt_time);
            SET currentTime = currentTime - INTERVAL 1 HOUR;
            SET crt_time = DATE_FORMAT(currenttime, '%d-%m %H');
            SET counter = counter + 1;
        END WHILE;
    END //
    DELIMITER ; 

I can't see anything to say that creating a temporary table isn't possible so what am I doing wrong.

https://dev.mysql.com/doc/refman/5.7/en/declare.html says:

DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

(emphasis mine)

Like the following:

CREATE PROCEDURE getLast24Hours()
    BEGIN
        DECLARE crt_time VARCHAR(8);
        DECLARE counter INT;
        DECLARE currentTime DATETIME;

        CREATE TABLE hours (`Hour` VARCHAR(8) NOT NULL, `Value` INT NOT NULL DEFAULT 0, PRIMARY KEY(`Hour`)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM