Loops in PL/SQL allow you to execute a block of code repeatedly until a specified condition is met. There are three types of loops in PL/SQL:
1.
BASIC LOOP (Runs indefinitely
until explicitly exited)
2.
WHILE LOOP (Runs while a condition
is true)
3.
FOR LOOP (Runs for a fixed
number of iterations)
BASIC
LOOP
A LOOP runs indefinitely unless you use EXIT
to stop it.
DECLARE
v_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 5; --
Stops when v_counter > 5
END LOOP;
END;
/
WHILE
LOOP
A
WHILE loop runs as long as the condition is TRUE.
DECLARE
v_counter NUMBER := 1;
BEGIN
WHILE v_counter <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || v_counter);
v_counter := v_counter + 1;
END LOOP;
END;
/
FOR
LOOP
A
FOR loop runs a fixed number of times, automatically handling the counter
variable.
BEGIN
FOR v_counter IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || v_counter);
END LOOP;
END;
/
Control Flow
Statements
1. LOOP
LABEL - Identify a loop.
2. CONTINUE
- Skip certain iterations.
3. GOTO
- Jump to a specific
label.
4. EXIT
WHEN Terminate the loop when a
condition is met.
DECLARE
v_order_id NUMBER
:= 0;
BEGIN
<<order_processing>> -- Loop Label
LOOP
v_order_id :=
v_order_id + 1;
-- CONTINUE:
Skip Order #3 (e.g., flagged for manual review)
IF v_order_id =
3 THEN
DBMS_OUTPUT.PUT_LINE('Skipping Order ID: ' || v_order_id || ' (Manual
Review Required)');
CONTINUE;
END IF;
-- GOTO: Jump
to end when Order #7 has a critical payment failure
IF v_order_id =
7 THEN
DBMS_OUTPUT.PUT_LINE('Critical Issue in Order ID: ' || v_order_id || ' -
Stopping Processing');
GOTO
stop_processing;
END IF;
DBMS_OUTPUT.PUT_LINE('Processing Order ID: ' || v_order_id);
-- EXIT WHEN:
Stop after 10 orders
EXIT WHEN
v_order_id = 10;
END LOOP;
<<stop_processing>>
-- Label to jump here with GOTO
DBMS_OUTPUT.PUT_LINE('Order processing stopped at Order ID: ' ||
v_order_id);
END;
/
No comments:
Post a Comment