在测试voucher的时候,我们的voucher规则是数据库自动生成一系列的voucherPIN码,然后在销售的时候随机取一个PIN码来进行销售,而在测试环境,数据库不进行自动生成这个步骤,都是测试人员一个一个地往数据库添加数据,今天测试的时候发现同事一个一个地往数据库添加数据,特别麻烦,于是为他写了一个程序,一跑就能自动生成上百个甚至上百万个,本来以为就几分钟的事,结果折腾了十几分钟才勉强搞定,不得不感叹一下,知识如果不经常用,很快就忘了,前阵子刚学的SQL程序块的知识都忘得差不多了,老被提示语法错误,又得翻翻书才终于搞定。这次写的程序中涉及到循环,我就把循环记下来,以后就算找也方便找一点,不用翻整本书^_^

PL/SQL中,常用的循环有三种:基本循环,for循环,while循环。

一、基本循环

基本循环的格式如下:

loop

         statements;//需要重复执行的语句

         exit [when condition]; //退出条件

end loop;

循环是用loop..end loop作为起始跟结束标志的,中间放的即是需要重复执行的语句,只有满足退出条件才会退出该循环,否则会一直循环地执行这些语句,因此退出条件的设定要注意。

例如:

declare
  i number :=
1;
begin
  loop
    dbms_output.put_line(
'this is the line ' || i);
    i := i +
1;
    exit when i >
3;
  end loop;
end;

打印结果如下:

this is the line 1
this is the line 2
this is the line 3

二、for循环

for循环的格式如下:

for counter in start..end loop

         statements; //需要重复执行的语句

end loop;

for循环使用一个循环计数器,从start开始,每次自增1,直到end结束,循环退出。

例如:

declare
begin
  for i in
1..3 loop
    dbms_output.put_line(
'this is the line ' || i);
  end loop;
end;

打印结果如下:

this is the line 1
this is the line 2
this is the line 3

三、while循环

while循环的格式如下:

while condition loop

         statements;

end loop;

例如:

declare
  i number :=
1;
begin
  while i <=
3 loop
    dbms_output.put_line(
'this is the line ' || i);
    i := i +
1;
  end loop;
end;

打印结果如下:

this is the line 1
this is the line 2
this is the line 3