一、条件控制语句
(1)条件语句I
if…then…end if形式1:
if <布尔表达式> then
…(pl/sql和sql)
…
end if;
(2)条件语句II
if…then…else … end if形式2:
if <布尔表达式> then
…(pl/sql和sql)
else
…
end if;
(3)条件控制语句III
if…then…elsif…then… else … end if形式3:
if <布尔表达式1> then
…(pl/sql和sql)
elsif <布尔表达式2> then
…
else
…
end if;
例子:
declare
theGrade number:= 88;
begin
if theGrade>=90 then
dbms_output.put_line('杰出');
elsif theGrade>=80 then
dbms_output.put_line('优秀');
elsif theGrade>=60 then
dbms_output.put_line('合格');
else
dbms_output.put_line('不及格');
end if;
end;
二、循环
循环语句分类
(1)简单循环
Loop
…(PL/SQl和SQL)
End loop;
可通过以下语句强行跳出循环:
1) if <布尔表达式> then exit;
2) exit when <布尔表达式>;
例子:
set serveroutput on;
declare
i number(8):=5;
begin
<<first_loop>>
loop
dbms_output.put_line('i = '||i);
i:= i-1;
exit first_loop when i = 0;
end loop;
dbms_output.put_line('LOOP循环已经结束!');
end;
(2)For循环
For n in num1..num2 Loop
… (PL/SQl和SQL)
End loop;
共循环 num2-num1+1 次;
例子:
beginFor循环
for i in -3..3 loop
dbms_output.put_line('i = '||i);
end loop;
dbms_output.put_line('FOR循环已经结束!');
end;
(3)While循环
控制条件为真时,重复执行循环体内的语句。
While <布尔表达式> loop
…(PL/SQl和SQL)
End loop;
例子:
declare
i number(8):=5;
While循环
begin
while(i > 0) loop
dbms_output.put_line('i = '||i);
i:=i-1;
end loop while_loop;
dbms_output.put_line('WHILE循环已经结束!');
end;
(4)Case
A.Case语句I
case
when <表达式1> then
…
when <表达式2> then
…
else
…
end case;
B.Case语句II
格式2:将列值转换成说明
Case 列名
when 值1 then 说明1
when 值2 then 说明2
…
else 其他
End;
例子:
set serveroutput Case语句on
declare
gender varchar2(20):= '男';
begin
case gender
when '男' then dbms_output.put_line('勇敢');
when '女' then dbms_output.put_line('漂亮');
else dbms_output.put_line('人妖');
end case;
end;
(5)Goto语句
goto 标签名语句
…
<<标签名>>
跳转规则:
• 1)同一程序块内跳转
• 2)子块跳到父块,不能父块跳到子块
• 3)不能从IF语句外跳入IF语句内
• 4)不能从While语句外跳入While语句内
• 5)不能从子程序外跳入子程序内
例子:
DECLARE
i number;
BEGIN
i:=5;
<<repeat_loop>> --循环点
DBMS_OUTPUT.PUT_LINE('i='||i);
i:=i-1;
IF i>0 THEN
GOTO repeat_loop; --小于5,就goto到repeat_loop
END IF;
END;