Table of contents
Break out of loop instructions
1. FOR loop
FOR 循环变量 IN 循环下限..循环上线 LOOP
-- 循环变量可以用任意的字母或者单词去替代
循环执行的逻辑题
END LOOP;
Calculate the cumulative value from 1-100
DECLARE
V_TEXT VARCHAR2(1000):='';
BEGIN
FOR X IN 1..10 LOOP
V_TEXT:=V_TEXT || 'O_0 ';
DBMS_OUTPUT.put_line(V_TEXT);
END LOOP;
END;
-- Notes on FOR loops:
1. Loop variables can only be referenced within the loop body.
2. Loop variables can only be assigned values each cycle between the upper and lower limits of IN, and cannot be reassigned using other words.
3. Words cannot be missing in the middle of the loop body. If you want to verify the loop, you can add them a NULL;
BEGIN
FOR X IN 1..20 LOOP
NULL;
END LOOP;
END;
-- LOOP loop
DECLARE
V_SUM NUMBER:=0;
BEGIN
LOOP
V_SUM:=V_SUM+1;
dbms_output.put_line(V_SUM);
EXIT WHEN V_SUM=5;
-- 如果这里不设定跳出循环条件,会陷入死循环
dbms_output.put_line(V_SUM);
END LOOP;
END;
-- WHILE loop
DECLARE
V_SUM NUMBER:=0;
BEGIN
WHILE V_SUM < 20 LOOP
DBMS_OUTPUT.PUT_LINE(V_SUM);
V_SUM:=V_SUM+1;
END LOOP;
END;
-- Summarize:
Three types of loops:
-- FOR loop, the loop variable is between the lower limit and the upper limit, iterates, and the loop terminates when it reaches the upper limit for the last time.
-- LOOP loop, the loop is endless until the conditions for jumping out of the loop are met. If the conditions are not set, it will fall into an infinite loop.
-- While loop, you must first set the conditions that meet the requirements before entering the loop. If the conditions are not set, it is easy to fall into an infinite loop.
TIPS:
* If the statement is executed at least once in the loop, LOOP is generally used;
* If the condition must be tested every time it is repeated, while is generally used.
* If the number of repetitions is known, FOR loop is generally used.
Break out of loop instructions
CONTINUE: Use the CONTINUE statement to skip the current loop iteration and continue executing the next loop
DECLARE
i NUMBER := 1;
BEGIN
FOR i IN 1..5 LOOP
IF i = 3 THEN
CONTINUE;
END IF;
DBMS_OUTPUT.PUT_LINE('i = ' || i);
END LOOP;
END;
EXIT: Use the EXIT statement to immediately terminate the loop
DECLARE
i NUMBER := 1;
BEGIN
FOR i IN 1..5 LOOP
IF i = 3 THEN
CONTINUE;
END IF;
DBMS_OUTPUT.PUT_LINE('i = ' || i);
END LOOP;
END;