从函数的Cursor中获取数据

时间:2017-05-22 07:38:31

标签: oracle11g cursor sql-function sys-refcursor

我创建了一个返回SYS_REFCURSOR的函数,

FUNCTION read_addresses (person_id NUMBER)
        RETURN SYS_REFCURSOR
    IS
        my_addresses   SYS_REFCURSOR;
    BEGIN
        OPEN my_addresses FOR
            SELECT commuter_name,
                   address_line,
                   city_name,
                   lat_lon,
                   my_dist,
              FROM carpool.addresses  addr
                   INNER JOIN CARPOOL.COMMUTERS comm
                       ON addr.COMMUTER_ID = comm.COMMUTER_ID
                   INNER JOIN CARPOOL.CITIES city
                       ON addr.city_id = city.CITY_ID
                   INNER JOIN carpool.coordinates coord
                       ON coord.COORD_ID = addr.COORD_ID
             WHERE comm.commuter_id = person_id AND addr.is_active = 1;

        RETURN my_addresses;
    END read_addresses;

我想制作一个匿名块来测试这个功能。我目前有什么:

DECLARE
    my_cursor    SYS_REFCURSOR;
    my_name      VARCHAR2 (100);
    my_address   VARCHAR2 (100);
    my_city      VARCHAR2 (100);
    my_latlon    VARCHAR2 (100);
    my_dist      NUMBER;
BEGIN
    my_cursor := carpool.irud.read_addresses (12);

    OPEN my_cursor;

    LOOP
        FETCH my_cursor
            INTO my_name,
                 my_address,
                 my_city,
                 my_latlon,
                 my_dist;

        EXIT WHEN my_cursor%NOTFOUND;
        DBMS_OUTPUT.put_line (my_name);
    END LOOP;

    CLOSE my_cursor;
END;

产生以下错误: 第11行第5列的表达式类型错误(我认为这是OPEN my_cursor行。

测试此功能并查看光标内容需要做什么?

对于这个问题,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

这里的问题是在调用函数后光标已经打开。无需编写OPEN my_cursor。消除此行可以解决问题。