循环控制语句

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语句


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值