PL/SQL Cursor Exercises: FETCH records with nested Cursors using Cursor FOR Loops
PL/SQL Cursor: Exercise-20 with Solution
Write a program in PL/SQL to FETCH records with nested Cursors using Cursor FOR Loops.
Nested Cursors Using Cursor FOR Loops
Sample Solution:
PL/SQL Code:
DECLARE
emp_dept_id departments.department_id%TYPE;
CURSOR cur_dept IS
SELECT *
FROM departments
WHERE manager_id IS NOT NULL
ORDER BY department_name;
CURSOR cur_emp IS
SELECT *
FROM employees
WHERE department_id = emp_dept_id;
BEGIN
FOR r_dept IN cur_dept
LOOP
emp_dept_id := r_dept.department_id;
DBMS_OUTPUT.PUT_LINE('----------------------------------');
DBMS_OUTPUT.PUT_LINE('Department Name : '||r_dept.department_name);
DBMS_OUTPUT.PUT_LINE('----------------------------------');
FOR r_emp IN cur_emp
LOOP
DBMS_OUTPUT.PUT_LINE('Employee: '||r_emp.last_name);
END LOOP;
END LOOP;
END;
/
Sample Output:
SQL> / ---------------------------------- Department Name : Accounting ---------------------------------- Employee: Higgins Employee: Gietz ---------------------------------- Department Name : Administration ---------------------------------- Employee: Whalen ---------------------------------- Department Name : Executive ---------------------------------- Employee: King Employee: Kochhar Employee: De Haan ...
Flowchart:
Improve this sample solution and post your code through Disqus
Previous: Write a program in PL/SQL to FETCH multiple records with the uses of nested cursor.
Next: Write a program in PL/SQL to print a list of managers and the name of the departments.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework