Example of PL/SQL Cursor FOR LOOP
Through two illuminating examples, complete with code snippets and detailed output explanations, we’ll showcase the remarkable versatility of this construct.
Example 1: Using FOR LOOP to Print Numbers.
The realm of the FOR LOOP, where this robust construct transforms into a dependable companion for effortlessly printing sequential numbers.
-- Using FOR LOOP to Print Numbers
DECLARE
-- Loop index
loop_index NUMBER := 1;
BEGIN
FOR loop_index IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || loop_index);
END LOOP;
END;
/
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
In this example, the FOR LOOP effortlessly prints the numbers from 1 to 5 using the DBMS_OUTPUT.PUT_LINE statement. The loop index dynamically changes in each iteration, providing a concise and readable solution for printing sequential numbers.
Example 2: Using FOR LOOP to Update Records.
the intricacies of how the loop index dynamically influences specific departments, showcasing the FOR LOOP’s inherent prowess in efficiently managing targeted updates.
-- Using FOR LOOP to Update Records
DECLARE
-- Loop index
loop_index NUMBER := 1;
BEGIN
FOR loop_index IN 1..3
LOOP
UPDATE employees
SET salary = salary * 1.1
WHERE department_id = loop_index;
END LOOP;
COMMIT;
END;
/
Output Explanation:
This example updates employees’ salaries in three different departments by multiplying their current salaries by 1.1. The loop index dynamically determines the specific departments being updated. The COMMIT statement finalizes the changes.
PL/SQL Cursor FOR LOOP
The PL/SQL FOR LOOP appears as a reliable ally, reducing the difficulties of recurring activities. This article walks you through the syntax, applications, and benefits of the FOR LOOP, using concrete examples to demonstrate its diverse possibilities within PL/SQL blocks. As we continue on this journey, we hope to provide developers with a better knowledge of how the FOR LOOP may streamline operations, increasing efficiency and clarity in creating powerful database procedures and routines. Join us on this trip to discover your true potential and improve your PL/SQL skills.