Advanced cursors |
Introduction
to Oracle SQL & PL/SQL |
The cursor FOR loop provides an elegant, simple syntax to to iterate over a result set. To underscore the advantages of cursor FOR loops, consider the following PL/SQL block which uses a basic loop.
|
SET SERVEROUTPUT ON |
Now examine the same query using a cursor FOR loop:
DECLARE |
You can use a cursor for loop without a declared cursor by including a query in the FOR statement. This can enable very compact code.
BEGIN |
While you can use EXIT statement within a FOR cursor loop, you should not use a cursor FOR loop if you may need to exit the LOOP prematurely. Use a basic or WHILE loop instead.
Cursors can use variables to adjust which rows they select when opened. Instead of hard-coding a value into the WHERE clause of a query, you can use a variable as a placeholder for a literal value. The variable placeholder will substituted with the value of the variable when the cursor is opened. This makes a query more flexible.
DECLARE |
This method works, but there is a better way. You can declare a cursor using parameters; then whenever you open the cursor, you pass in appropriate parameters. This technique is just as flexible, but is easier to maintain and debug. The above example adapted to use a parameterized cursor:
DECLARE |
Parameterized cursors are open easier to debug in larger PL/SQL blocks. This is because the the declaration of the cursor body is often far from where the cursor is opened, but processing of the cursor's result set is usually close to where the cursor is opened.
An example which combines a cursor FOR loop with a parameterized query:
DECLARE |