Search code examples
oracle-databaseplsqldatabase-cursor

How to access different columns of a different tables using cursor after a join has been made on a particular column name in the tables


So I am having issues in understanding how can one access different column names using a cursor in which a join operation has been made on three different tables over a single common column.

For example

DECLARE
  CURSOR joined_table_cur IS
    SELECT a.col1, a.col2, b.col5, c.col7 ...
    FROM table1 a
    JOIN table2 b ON a.col1 = b.col1 JOIN
    table3 c on b.col1 = c.col1 
;

  joined_table_rec joined_table_cur%ROWTYPE;
BEGIN
  FOR joined_table_rec IN joined_table_cur
  LOOP    
   -- how to access col7 from table3 ie c in this cursor--
  END LOOP;
END;

I am unable to understand how to do this.


Solution

  • To loop through cursor rows in your sample all you should do is to use second type of looping in code below and reference the columns using already declared variable joined_table_rec - for col1 it is joined_table_rec.col1, for col2 joined_table_rec.col2 ... and so on.
    If you want to use FOR LOOP then you don't need to declare joined_table_rec variable as the for loop would create the variable itself - just give the name - rec2 in code below. Below is example for two ways how to loop the cursor:

    SET SERVEROUTPUT ON
    DECLARE
      CURSOR cur IS
        SELECT *
        FROM
        (
              Select 1 "COL_ID", 'Name 1' "COL_NAME", 'Somethong else 1' "COL_ELSE" From Dual Union All
              Select 2 "COL_ID", 'Name 2' "COL_NAME", 'Somethong else 2' "COL_ELSE" From Dual Union All
              Select 3 "COL_ID", 'Name 3' "COL_NAME", 'Somethong else 3' "COL_ELSE" From Dual
        );
        rec cur%ROWTYPE;
        m_sql VarChar2(500);
    BEGIN
    
      FOR rec2 IN cur LOOP
          DBMS_OUTPUT.PUT_LINE(rec2.COL_ID);
      END LOOP;
      
    
      OPEN cur;
      LOOP   
            FETCH cur Into rec;
            EXIT WHEN cur%NOTFOUND;
            DBMS_OUTPUT.PUT_LINE(rec.COL_NAME);
      END LOOP;
      CLOSE cur;
    END;
    
    Result: 
    anonymous block completed
    1
    2
    3
    Name 1
    Name 2
    Name 3
    

    More about it here.