PL/SQL - FOR LOOP Statement (On Cursor, Sequence, ...)

> Procedural Languages > PL/SQL - (Procedure Language|PL) SQL

1 - About

The for statement has two forms. It can be use with:

  • a sequence to loop though a sequence of number or through a collection
  • a cursor

You break the for loop with an

EXIT

statement.

3 - Syntax

  • Sequence Syntax
FOR INDEX IN [REVERSE] lower_bound .. upperd_bound LOOP
statement
END LOOP [label]
  • Cursor Syntax
FOR RECORD IN ([SELECT statement|explicit CURSOR]) LOOP
statement WITH RECORD.column 
END LOOP [label]

where the in condition contains

Advertising

4 - Sequence

4.1 - Basic

SET SERVEROUTPUT ON
BEGIN
FOR i IN 1..3 LOOP
  DBMS_OUTPUT.PUT_LINE (i);
END LOOP;
END;
/
1
2
3

4.2 - Collection

with a collection

DECLARE
   TYPE at_most_twelve_t IS VARRAY (12) OF VARCHAR2 (100);
   l_months   at_most_twelve_t;
BEGIN
 
   l_months = at_most_twelve_t('January','February','March');
 
   FOR indx IN 1 .. l_months.COUNT
   LOOP
      DBMS_OUTPUT.put_line (l_months (indx));
   END LOOP;
 
END;
/

5 - Cursor

On Cursor FOR Loops.

Recommendations:

  • If you expect to retrieve just one row, use an implicit SELECT INTO query
  • If you expect to retrieve multiple rows of data and you know the upper limit (as in, “I will never get more than 100 rows in this query”), use BULK COLLECT into a collection of type varray whose upper limit matches what you know about the query.
  • If you expect to retrieve multiple rows of data and you do not know the upper limit, use BULK COLLECT with a FETCH statement that relies on a LIMIT clause to ensure that you do not consume too much per-session memory.

5.1 - Implicit

Implicit Cursor FOR LOOP statement: See Query Result Set Processing With Cursor FOR LOOP Statements

SET SERVEROUTPUT ON
BEGIN
FOR i IN (SELECT 'Nico' AS name  FROM dual UNION ALL SELECT 'Nickeau' FROM dual) LOOP
  DBMS_OUTPUT.PUT_LINE (i.name);
END LOOP;
END;
/
Nico
Nickeau
Advertising

5.2 - Explicit

DECLARE
  CURSOR c1 IS
    SELECT last_name, job_id FROM employees
    WHERE job_id LIKE '%CLERK%' AND manager_id > 120
    ORDER BY last_name;
BEGIN
  FOR item IN c1
  LOOP
    DBMS_OUTPUT.PUT_LINE
      ('Name = ' || item.last_name || ', Job = ' || item.job_id);
  END LOOP;
END;
/

With parameters:

DECLARE
  CURSOR c1 (job VARCHAR2, max_wage NUMBER) IS
    SELECT * FROM employees
    WHERE job_id = job
    AND salary > max_wage;
BEGIN
  FOR person IN c1('ST_CLERK', 3000)
  LOOP
     -- process data record
    DBMS_OUTPUT.PUT_LINE (
      'Name = ' || person.last_name || ', salary = ' ||
      person.salary || ', Job Id = ' || person.job_id
    );
  END LOOP;
END;
/

6 - Reference

lang/plsql/for.txt · Last modified: 2017/09/06 22:18 by gerardnico