Search code examples
oracle11gcursorsql-functionsys-refcursor

Fetch data from a Cursor that comes from a Function


I created a function that returns a 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;

And I want to make an anonymous block to test this function. What I currently have:

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;

Yields the following error: Expression is of wrong type on line 11, column 5 (I think that is the OPEN my_cursor line.

What do I need to do to test this function and see the contents of the cursor?

I will appreciate any help with this problem.


Solution

  • The problem here is that the cursor is already open after calling the function. There is no need to write OPEN my_cursor. Eliminating this line fixes the problem.