PL/SQL flow control statement
This blog introduces PL/SQL flow control statements, including the following three types
Control statements: IF statement
Loop statements: LOOP statement, EXIT statement
Sequence statements: GOTO statement, NULL statement
A conditional statement
(1) Grammar
①
IF<布尔表达式 > THEN
PL/SQL和 SQL 语句
END IF;
②
IF<布尔表达式 > THEN
PL/SQL和 SQL 语句
ELSE
其它语句
END IF;
③
IF<布尔表达式 > THEN
PL/SQL和 SQL 语句
ELSIF
< 其它布尔表达式 > THEN
其它语句
ELSIF< 其它布尔表达式 > THEN
其它语句
ELSE
其它语句
END IF;
注意:ELSIF别写错
(2) The case is as follows:
DECLARE
v_empno emp.empno%TYPE;
V_salary emp.sal%TYPE;
V_comment VARCHAR2(35);
BEGIN
SELECT sal INTO v_salary FROM emp WHERE empno=v_empno;
IF v_salary<1500 THEN
V_comment:= ‘ Fairly less’;
ELSIF v_salary <3000 THEN
V_comment:= ‘A little more’;
ELSE
V_comment:= ‘Lots of salary’;
END IF;
DBMS_OUTPUT.PUT_LINE(V_comment);
END;
Two case expressions
(1) Grammar
CASE selector
WHEN expression1 THEN result1
WHEN expression2 TH EN result2
WHEN expressionN THEN resultN
[ ELSE resultN+1]
END
(2) Case
DECLARE
V_grade char(1)
V_appraisal VARCHAR2(20);
BEGIN
V_appraisal :=
CASE v_grade
WHEN ‘A’ THEN ‘Excellent’
WHEN ‘B’ THEN ‘Very Good’
WHEN ‘C’ THEN ‘Good’
ELSE ‘No suc h grade’
END;
DBMS_OUTPUT.PUT_LINE(‘Grade:‘||v_grade||’ Appraisal: ‘|| v_appraisal);
END;
Three cycles
(1) Simple loop,
you can use exit to exit the loop
LOOP
要执行的语句
EXIT WHEN <条件语句>;/*条件满足,退出循环语句*/
END LOOP;
The case is as follows:
DECLARE
int NUMBER(2) :=0;
BEGIN
LOOP
int := int + 1;
DBMS_OUTPUT.PUT_LINE('int 的当前值为 :'||int);
EXIT WHEN int =10;
END LOOP;
END;
(2) While loop
Syntax:
WHILE<布尔表达式 > LOOP
要执行的语句
END LOOP;
Case:
DECLARE
x NUMBER :=1;
BEGIN
WHILE x<=10 LOOP
DBMS_OUTPUT.PUT_LINE('X 的当前值为 x);
x:= x+1;
END LOOP;
END;
(3) Digital loop
Syntax:
each loop, loop variable automatically increases by 1; using the keyword REVERSE, loop variable automatically decreases by 1. The numbers following IN REVERSE must be in ascending order, and must be integers, not variables or expressions. You can use EXIT to exit the loop.
FOR 循环计数器 IN [REVERSE ] 下限 .. 上限 LOOP
要执行的语句
END LOOP;
Case:
BEGIN
FOR int in 1..10 LOOP
DBMS_ OUTPUT.PUT_LINE('int 的当前值为 : '||int);
END LOOP;
END;
(4) The label and GOTO end the loop.
Syntax:
GOTO label;
. . . . .
<<label>>/*标号是用 括起来的标识符*/
Case study
DECLARE
V_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('V_counter 的当前值为 :'||V_counter);
V_counter := v_counter + 1;
IF v_counter > 10 THEN
GOTO l_ENDofLOOP;--跳转标识
END IF;
END LOOP;
<<l_ENDofLOOP>>
DBMS_OUTPUT.PUT_LINE('V_counter 的当前值为 :'||V_counter);
END ;
(5) NULL statement
In a PL/SQL program, a null statement can be used to illustrate the meaning of not having to do anything, which is equivalent to a placeholder, which can make certain statements meaningful and improve the readability of the program.
DECLARE
. . .
BEGIN
…
IF v_num IS NULL THEN
GOTO print1;
END IF;
…
<<print1>>
NULL;--不需要处理任何数据。
END;