4.2.2 loop 循环并使用exit退出循环
declare
v_count number(2) :=0;
begin
loop
v_count := v_count +1;
dbms_output.put_line('行' || v_count || ':hello PL/sql!');
if v_count = 10
then
exit;--使用exit退出循环
end if;
end loop;
dbms_output.put_line('循环已经退出了!');
end;
4.2.3使用exit-when 退出循环
declare
v_count number(2) :=0;
begin
loop
v_count := v_count +1;
dbms_output.put_line('行' || v_count || ':hello PL/sql!');
exit when v_count=10;--使用exit when来退出循环
end loop;
dbms_output.put_line('循环已经退出了!');
end;
4.2.4 使用CONTINUE继续执行循环
declare
x number :=0;
begin
loop
dbms_output.put_line('内部循环值: x= '|| to_char(x));
x := x+1;
if x < 3
then
continue;--使用continue停止本次循环,跳过后面代码,重新开始循环
end if;
dbms_output.put_line('continue之后的值: x= '|| to_char(x));
exit when x = 5;
end loop;
dbms_output.put_line('循环体结束之后的值: x= '|| to_char(x));
end;
declare
x number :=0;
begin
loop
dbms_output.put_line('内部循环值: x= '|| to_char(x));
x := x+1;
continue when x < 3; --退出本次循环 也就是下面的不执行直接进入新的循环
dbms_output.put_line('continue之后的值: x= '|| to_char(x));
exit when x = 5;
end loop;
dbms_output.put_line('循环体结束之后的值: x= '|| to_char(x));
end;
4.2.5 while-loop 循环
declare
v_count PLS_INTEGER := 1;
begin
while v_count <= 5 --条件为真才进入循环
loop
dbms_output.put_line('while循环索引值 '|| v_count);
v_count := v_count +1;
end loop;
end;
4.2.6 for-loop循环
declare
v_total integer := 0;
begin
for i in 1 .. 3 --没分号
loop
v_total := v_total + 1;
dbms_output.put_line('循环计数器值 '|| i);
end loop;
dbms_output.put_line('循环总计 '|| v_total);
end;
-- 如果循环的上界和下界一致,循环将仅执行一次,例如
-- for i in 2 .. 2,仅执行一次
declare
v_total integer := 0;
begin
for i in reverse 1 .. 3 --使用reverse从高到低进行循环
loop
v_total := v_total + 1;
dbms_output.put_line('循环计数器值 '|| i);
end loop;
dbms_output.put_line('循环总计 '|| v_total);
end;
declare
v_counter integer := &counter;
begin
for i in 1 .. v_counter
loop
dbms_output.put_line('循环计数 '|| i);
end loop;
end;
-- 循环语句的几点建议
-- 1.不要在for 和 while循环中使用exit 或 exit when 子句
-- 2.注意不要创建死循环,要总确保循环具有退出条件
-- 3.在循环内部尽量避免使用return 或 goto语句
循环控制语句
最新推荐文章于 2024-07-21 02:23:05 发布