LOOPS

LOOP
…executable statement(s)
EXIT WHEN condition
END LOOP

DECLARE
counter NUMBER(3) := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(TO_CHAR(counter) || ' ');
EXIT WHEN counter >= 20;
counter := counter + 1;
END LOOP;
END;
/

WHILE condition LOOP
…executable statement(s)
END LOOP

DECLARE
counter NUMBER(3) := 1;
BEGIN
WHILE (counter < 20) LOOP
DBMS_OUTPUT.PUT_LINE(TO_CHAR(counter) || ' ');
counter := counter + 1;
END LOOP;
END;
/

FOR LOOP counter_variable IN LOWER_LIMIT..UPPER_LIMIT LOOP
…executable statement(s)
END LOOP

With FOR LOOP we do not need to previously declare the counter variable.

BEGIN
FOR counter IN 1..19 LOOP
DBMS_OUTPUT.PUT_LINE(TO_CHAR(counter) || ' ');
END LOOP;
END;
/

FOR record_index in cursor_name
LOOP
…executable statement(s)
END LOOP;

DECLARE
cursor c1 is
select name
from employees;
BEGIN
FOR employee_rec in c1
LOOP
DBMS_OUTPUT.PUT_LINE(employee_rec.name);
END LOOP;
END;

CONTINUE command
CONTINUE statement makes the loop finish current iteration and go with the next one. It is also possible to use labels with loops to determine which one should be skipped in CONTINUE statement.

DECLARE
BEGIN
<>
FOR outer_counter IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE(outer_counter);
<>
FOR inner_counter IN 10..13 LOOP
CONTINUE outer_loop WHEN outer_counter > 1 AND inner_counter = 12;
DBMS_OUTPUT.PUT_LINE(‘…’||inner_counter);
END LOOP;
END LOOP;
END;

1
…10
…11
…12
…13
2
…10
…11
3
…10
…11

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: