Search code examples
databaseoraclestored-procedurescursor

Traverse through inner join result using cursor


I am very new to the oracle database stored procedure, so please forgive me if i am asking very simple or basic question.

I want to traverse through inner join result set which was produced in procedure using cursor.

I have created one procedure which have a simple SQL select query joing tow table and selection fields from both the table.

CREATE OR REPLACE PROCEDURE demoprocedure(crsr out SYS_REFCURSOR)  
AS 
      BEGIN
      OPEN crsr FOR
        SELECT 
            TABLE1.field1, TABLE2.field2, TABLE1.fields11, TABLE2.field22
        FROM 
            TABLE1 INNER JOIN   
            TABLE2   
        ON 
            TABLE1.field12 = TABLE2.field12
END demoprocedure;

I want to traverse this result set using cursor, here is what i have tried

DECLARE
  crsr SYS_REFCURSOR;
  temp SYS_REFCURSOR;
BEGIN
  demoprocedure(crsr);
  LOOP
    FETCH crsr INTO temp;
        EXIT WHEN crsr%NOTFOUND;
        Dbms_Output.Put_Line('Fields1 is : ' || temp.field1);
  END LOOP;
  CLOSE crsr;
END;

But this is not working, well i have tried creating custom object but is also gives error.

Expected result:

Fields1 is : 1
Fields1 is : 2
Fields1 is : 3

Solution

  • The issue is with the declaration of the temp variable. You can fetch the content of the SYS_REFCURSOR in a local variable and then display it as following:

    Procedure:

    SQL> CREATE OR REPLACE PROCEDURE DEMOPROCEDURE (
      2      CRSR OUT   SYS_REFCURSOR
      3  ) AS
      4  BEGIN
      5      OPEN CRSR FOR SELECT
      6                        'ABC' AS COL1,
      7                        'BCD' AS COL2,
      8                        'CDE' AS COL3,
      9                        'DEF' AS COL4
     10                    FROM
     11                        DUAL;
     12
     13  END DEMOPROCEDURE;
     14  /
    
    Procedure created.
    

    Testing it (Loop through it)

    SQL> SET SERVEROUT ON;
    SQL> DECLARE
      2      CRSR     SYS_REFCURSOR;
      3      V_COL1   VARCHAR2(100);
      4      V_COL2   VARCHAR2(100);
      5      V_COL3   VARCHAR2(100);
      6      V_COL4   VARCHAR2(100);
      7  BEGIN
      8      DEMOPROCEDURE(CRSR);
      9      LOOP
     10          FETCH CRSR INTO
     11              V_COL1,
     12              V_COL2,
     13              V_COL3,
     14              V_COL4;
     15          EXIT WHEN CRSR%NOTFOUND;
     16          DBMS_OUTPUT.PUT_LINE('Fields1 is : ' || V_COL1);
     17          DBMS_OUTPUT.PUT_LINE('Fields2 is : ' || V_COL2);
     18          DBMS_OUTPUT.PUT_LINE('Fields3 is : ' || V_COL3);
     19          DBMS_OUTPUT.PUT_LINE('Fields4 is : ' || V_COL4);
     20      END LOOP;
     21
     22      CLOSE CRSR;
     23  END;
     24  /
    Fields1 is : ABC
    Fields2 is : BCD
    Fields3 is : CDE
    Fields4 is : DEF
    
    PL/SQL procedure successfully completed.
    
    SQL>
    

    Cheers!!