加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Oracle PL/SQL中的循环处理(sql for循环)

发布时间:2020-12-12 15:51:33 所属栏目:百科 来源:网络整理
导读:PL/SQL也和我们常用的编程语言一样,提供了While、For等循环,我们建几个例子来说明演示下。 首先是While循环: --while循环 procedure loop_while( start_value in number ,end_value number ) is current_value number : = start_value; begin while curre

PL/SQL也和我们常用的编程语言一样,提供了While、For等循环,我们建几个例子来说明演示下。

首先是While循环:

--while循环
procedure loop_while
(
   start_value in number,end_value number
)
is
   current_value number := start_value;
begin
  while current_value <=end_value
  loop 
     dbms_output.put_line('now number:' || current_value);
     current_value:=current_value+1;
  end loop;           
end loop_while;

指定循环的初始值和结束值之后,就可以看到将这2个值之间的数字一行行打印出来了;当然只要while循环条件的求值结果是true,循环就会继续下去,

如果求值条件为false或者null,循环就会终止。这个循环条件每执行一次循环体之前都会先进行判断,因此while循环并不能保证循环体一定能被执行。

所以如果我们无法提前预知所需要巡检的次数的情况下,就可以使用While来进行循环处理。

For循环有2种,分别是数值型FOR循环和游标型FOR循环:

--数值型For循环 procedure loop_num_for ( lowest is begin FOR even_number in lowest .. highest--升序 loop --处理非平滑增长的索引 if mod(even_number,2)=0 then dbms_output.put_line(|| even_number); end if; end loop; end loop_num_for; 这种循环在开始的时候就已经知道循环的次数了,注意这里不需要声明循环索引,因为PL/SQL会自动隐式的用一个integer类型的局部变量作为它的循环索引;

如果要降序循环,必须加上reverse关键字,并且循环上边界和下边界的顺利无需改变:

 in reverse lowest .. highest
 loop
    dbms_output.put_line('now number:' || even_number);
 end loop;    

另外需要说明的是,数值型FOR循环中,索引总是以1为单位递增或递减,所以如果我们的循环条件并非如此理想的平滑增长,我们就必须用一些逻辑代码或者技巧来

达到我们的目的。

如果我们需要对很多行记录做处理时,就可以使用游标型FOR循环:

--游标型For循环
procedure loop_cursor_for begin declare cursor userinfo_cur is select * from userinfo_table; begin FOR userinfo_rec in userinfo_cur loop dbms_output.put_line('username is:' || userinfo_rec.user_name); end loop; end; end loop_cursor_for; 当游标中的所有记录都取出来后,FOR循环就会自动终止,这里不用显示OPEN、CLOSE游标,PL/SQL引擎会自动处理。

上面的循环语句都可以用EXIT 或者 EXIT WHEN来终止其循环,但最好不要这样做,因为这样可能会造成循环的逻辑出现问题,最终造成SQL代码难于跟踪和调试。

最后附上测试用的SQL:

create or replace package body LOOP_TEST_DEMO IS
  --while循环
  procedure loop_while(start_value number,end_value number) is
    current_value = start_value;
  begin
    <= end_value loop
      dbms_output.put_line('now number:' || current_value);
      current_value := current_value + 1;
    end loop;
  end loop_while;

  数值型For循环
  procedure loop_num_for(lowest is
  in lowest .. highest
    升序
     loop
      dbms_output.put_line(even_number);
      处理非平滑增长的索引
      2) = 0 then
        dbms_output.put_line(if;
    end loop;
    降序
    reverse lowest .. highest loop
      dbms_output.put_line(|| even_number);
    end loop_num_for;

  游标型For循环
  procedure loop_cursor_for declare
      is
        from greenet_user_info;
    begin
      in userinfo_cur loop
        dbms_output.put_line(username is:user_name);
      end;
  end loop_cursor_for;

end LOOP_TEST_DEMO;
 
  
 
  
转载:http://www.cnblogs.com/maoniu602/archive/2013/03/01/2938758.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读