使用存储过程删除临时表

时间:2010-02-17 11:43:45

标签: mysql stored-procedures

我一直在尝试创建一个自动删除临时表的存储过程。

CREATE PROCEDURE DeleteTemp()
BEGIN
DECLARE no_more_rows BOOLEAN;
DECLARE loop_cntr INT DEFAULT 0;
DECLARE num_rows INT DEFAULT 0;


DECLARE tmptablename VARCHAR(100);
DECLARE tmpTables CURSOR FOR
    SELECT TABLE_NAME
    FROM information_schema.TABLES
    WHERE TABLE_SCHEMA='myDB' AND TABLE_NAME LIKE 'tmp%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
OPEN tmpTables;
SELECT FOUND_ROWS() into num_rows;
the_loop: LOOP
    FETCH tmpTables INTO tmptablename;
    DROP TABLE tmptablename;
    IF no_more_rows THEN
        CLOSE tmpTables;
        LEAVE the_loop;
    END IF;
END LOOP the_loop;
END

但是,我得到的只是:

查询:调用DeleteTemp 错误代码:1051 未知表'tmptablename'

如何将变量tmptablename正确传递到“DROP TABLE”命令?


修复了使用预备语句。

CREATE
    PROCEDURE DeleteTemp()
    BEGIN
    DECLARE no_more_rows BOOLEAN;
    DECLARE loop_cntr INT DEFAULT 0;
    DECLARE num_rows INT DEFAULT 0;


    DECLARE tmptablename VARCHAR(100);
    DECLARE tmpTables CURSOR FOR
        SELECT TABLE_NAME
        FROM information_schema.TABLES
        WHERE TABLE_SCHEMA='MY_SCHEMA'
            AND TABLE_NAME LIKE 'tmp%';
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
    OPEN tmpTables;
    SELECT FOUND_ROWS() INTO num_rows;

    the_loop: LOOP
        FETCH tmpTables INTO tmptablename;
        IF no_more_rows THEN
            CLOSE tmpTables;
            LEAVE the_loop;
        ELSE
            SET @a:=CONCAT('DROP TABLE ',tmptablename);
            PREPARE stmt1 FROM @a;
            EXECUTE stmt1;
            DEALLOCATE PREPARE stmt1;
        END IF;
    END LOOP the_loop;
    END

2 个答案:

答案 0 :(得分:2)

您是否看过 PREPARE EXECUTE 命令。这就像执行DYNAMIC SQL

SQL Syntax for Prepared Statements

  

以下SQL语句可以   在准备好的陈述中使用:ALTER   TABLE,CALL,COMMIT,CREATE INDEX,   CREATE TABLE,DELETE,DO,DROP INDEX,    DROP TABLE ,INSERT,RENAME TABLE,   REPLACE,SELECT,SET,UPDATE等等   SHOW陈述。分析表,   OPTIMIZE TABLE和REPAIR TABLE是   从MySQL 5.0.23开始也支持。

答案 1 :(得分:0)

这可能不是您所追求的,但您是否知道您的临时表仅对创建它们的连接可见,并且一旦该连接关闭后将自动删除?