您的位置:首页 > 数据库

PL/SQL的循环控制

2012-09-07 15:49 274 查看
在测试voucher的时候,我们的voucher规则是数据库自动生成一系列的voucher的PIN码,然后在销售的时候随机取一个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
本文出自 “sunmoon小筑” 博客,请务必保留此出处http://sunmoonrili.blog.51cto.com/5265851/984615
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: