Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

PL/SQL Cursor Exercises: FETCH multiple records and more than one columns from different tables

PL/SQL Cursor: Exercise-18 with Solution

Write a program in PL/SQL to FETCH multiple records and more than one columns from different tables.

Below example we are trying to fetch department names and employee names.

Sample Solution:

PL/SQL Code:

DECLARE
    CURSOR cur_emp_name IS
      SELECT first_name,
             last_name,
             department_name
      FROM   employees e,
             departments d
      WHERE  d.department_id = e.department_id;
    v_emp_rec cur_emp_name%ROWTYPE;
BEGIN
    OPEN cur_emp_name;
    LOOP
        FETCH cur_emp_name INTO v_emp_rec;
        exit WHEN cur_emp_name%NOTFOUND;
        dbms_output.Put_line('Name:  '
                             || v_emp_rec.first_name
                             || '  '
                             ||v_emp_rec.last_name
                             || '   ::   department: '
                             || v_emp_rec.department_name);
    END LOOP;
    CLOSE cur_emp_name;
END; 
 /

Sample Output:

SQL> /
Name:  Jennifer  Whalen   ::   department: Administration
Name:  Pat  Fay   ::   department: Marketing
Name:  Michael  Hartstein   ::   department: Marketing
Name:  Sigal  Tobias   ::   department: Purchasing
Name:  Karen  Colmenares   ::   department: Purchasing
Name:  Shelli  Baida   ::   department: Purchasing
Name:  Den  Raphaely   ::   department: Purchasing
Name:  Alexander  Khoo   ::   department: Purchasing
Name:  Guy  Himuro   ::   department: Purchasing
Name:  Susan  Mavris   ::   department: Human Resources
Name:  Kevin  Feeney   ::   department: Shipping
Name:  Jean  Fleaur   ::   department: Shipping
Name:  Adam  Fripp   ::   department: Shipping
...

Flowchart:

Flowchart: PL/SQL Cursor Exercises - FETCH multiple records and more than one columns from  different tables

Improve this sample solution and post your code through Disqus

Previous: Write a program in PL/SQL to FETCH multiple records and more than one columns from the same table.
Next: Write a program in PL/SQL to FETCH multiple records with the uses of nested cursor.

What is the difficulty level of this exercise?