4

在 MySQL 存储过程中,如何为从 select 语句创建的临时表声明游标。谢谢,

DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_foo`$$
CREATE PROCEDURE sp_foo()
BEGIN   
    DROP TEMPORARY TABLE IF EXISTS `TmpMyTable`;
    CREATE TEMPORARY TABLE `TmpMyTable` (
        `id`            INT(11) NOT NULL AUTO_INCREMENT,
        `person_id`     INT(11) NOT NULL,
        `first_name`    VARCHAR(60) NOT NULL,
        `last_name`     VARCHAR(60) NOT NULL,
        PRIMARY KEY  (`id`),
        INDEX `idx_first_name` (`person_id`),
        INDEX `idx_first_name` (`first_name`)
    ) ENGINE=MYISAM         
        SELECT 
            id AS `person_id`,
            first_name,
            last_name
        FROM person
    ;

    DECLARE _person_id INT(11); 
    DECLARE personCursor CURSOR 
    FOR 
        SELECT * FROM TmpMyTable;       

    OPEN personCursor;
    LOOP
        FETCH personCursor INTO _person_id;

        ...

    END LOOP;   
    END$$
DELIMITER ;
4

2 回答 2

3

在您的示例中,在创建临时表之前进行游标声明。似乎不合逻辑,但它有效。

于 2016-03-28T11:53:52.080 回答
0

您可以创建两个单独的过程。像这样:

DELIMITER $$
DROP PROCEDURE IF EXISTS `tmp_tbl`$$
CREATE PROCEDURE tmp_tbl()
BEGIN   
    DROP TEMPORARY TABLE IF EXISTS `TmpMyTable`;
    CREATE TEMPORARY TABLE `TmpMyTable` (
        `id`            INT(11) NOT NULL AUTO_INCREMENT,
        `person_id`     INT(11) NOT NULL,
        `first_name`    VARCHAR(60) NOT NULL,
        `last_name`     VARCHAR(60) NOT NULL,
        PRIMARY KEY  (`id`),
        INDEX `idx_first_name` (`person_id`),
        INDEX `idx_first_name` (`first_name`)
    ) ENGINE=MYISAM         
        SELECT 
            id AS `person_id`,
            first_name,
            last_name
        FROM person
    ;   
    END$$
DELIMITER ;
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_foo`$$
CREATE PROCEDURE sp_foo()
BEGIN   
    DECLARE _person_id INT(11); 
    DECLARE personCursor CURSOR 
    FOR 
        SELECT * FROM TmpMyTable;       

    OPEN personCursor;
    LOOP
        FETCH personCursor INTO _person_id;

        ...

    END LOOP;   
    END$$
DELIMITER ;

稍后您可以按顺序调用它们。

call tmp_tbl();
call sp_foo();

实际上在你之后BEGINPROCEDURE需要完成你的声明部分。

于 2020-06-04T07:57:32.470 回答