MySQL游标不会获取数据

时间:2014-02-18 09:11:34

标签: mysql function stored-procedures cursor

我使用http://www.mysqltutorial.org/mysql-cursor/中的以下示例来连接查询结果并将其作为字符串返回到mysql数据库中。

当我在程序外执行查询时,它返回电子邮件结果列表。但是当我在过程或函数中使用游标执行相同的查询时,结果为空。

有什么区别?

CREATE PROCEDURE build_email_list (INOUT email_list varchar(4000))
BEGIN

    DECLARE v_finished INTEGER DEFAULT 0;
        DECLARE v_email varchar(100) DEFAULT "";

    -- declare cursor for employee email
    DEClARE email_cursor CURSOR FOR 
        SELECT email FROM employees;

    -- declare NOT FOUND handler
    DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET v_finished = 1;

    OPEN email_cursor;

    get_email: LOOP

        FETCH email_cursor INTO v_email;

        IF v_finished = 1 THEN 
            LEAVE get_email;
        END IF;

        -- build email list
        SET email_list = CONCAT(v_email,";",email_list);

    END LOOP get_email;

    CLOSE email_cursor;

END

1 个答案:

答案 0 :(得分:2)

您可以使用一个查询执行此操作:

SELECT GROUP_CONCAT(email SEPARATOR ';') AS email_list FROM employees;