SQL循环获取空值

时间:2015-01-10 08:53:43

标签: mysql sql loops select cursor

在下一部分代码中,我使用游标和循环生成与搜索查询匹配的用户列表, 但我得到null值,为什么?

BEGIN
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE ids TEXT;
    DECLARE response TEXT;
    DECLARE ids_cursor CURSOR FOR
        SELECT id 
        FROM user WHERE email LIKE CONCAT('%',value,'%') 
        OR lastname LIKE CONCAT('%',value,'%') 
        OR name LIKE CONCAT('%',value,'%');
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 2;

    OPEN ids_cursor;
    get_ids: LOOP

        FETCH ids_cursor INTO ids;

        IF finished = 2 THEN
            LEAVE get_ids;
        END IF;

        SET response = CONCAT(ids,";",response);

    END LOOP get_ids;
    CLOSE ids_cursor;

    RETURN response;
END

1 个答案:

答案 0 :(得分:1)

您无需使用用户定义的功能,您可以通过以下查询使用GROUP_CONCAT()功能直接获取ID。

SELECT GROUP_CONCAT(id SEPARATOR ';') AS response
FROM user 
WHERE email LIKE CONCAT('%',value,'%') 
   OR lastname LIKE CONCAT('%',value,'%') 
   OR name LIKE CONCAT('%',value,'%');