FOR Loops
Structure:
[label] FOR loop_counter IN [REVERSE] lower_bound..upper_bound LOOP
group_of_statements
END LOOP [label];
Lower/upper bounds are inclusive. Counter is implicitly initialized as PLS_INTEGER.
Example:
DECLARE
l_sum NUMBER := 0;
BEGIN
FOR l_counter IN 1..3 LOOP
l_sum := l_sum + l_counter;
END LOOP;
END;
Can use literals, variables, or expressions for loop bounds:
DECLARE
l_lower NUMBER := 2;
l_upper NUMBER := 5;
BEGIN
FOR l_counter in l_lower..(l_upper/l_lower) LOOP
dbms_output.PUT_LINE(l_counter);
END LOOP;
END;
To increment using a different step size:
DECLARE
l_step_counter NUMBER;
BEGIN
FOR l_counter in 1..3 LOOP
l_step_counter := l_counter * 2;
END LOOP;
END;
Example using count():
CREATE TABLE departments(
dept_id NUMBER NOT NULL PRIMARY KEY,
dept_name VARCHAR2(60));
INSERT INTO departments (dept_id, dept_name) values (1, 'Sales');
INSERT INTO departments (dept_id, dept_name) values (2, 'IT');
DECLARE
l_dept_count NUMBER;
BEGIN
SELECT count(*)
INTO l_dept_count
FROM departments;
FOR l_counter IN 1..l_dept_count LOOP
dbms_output.PUT_LINE(l_counter);
END LOOP;
END;