循环语句
循环语句
loop循环语句
loop
执行块;
exit 【when 表达式;】//结束循环
end loop;
有条件退出:exit 后面+when
无条件退出:exit
案列
declare
a int ;
begin
a:=1;
loop
dbms_output.put_line(a);
a:=a+1;
exit when a>10;
end loop;
end;
while循环语句
while condition loop
执行体;
end loop;
condition :返回true,循环,返回false,退出循环
案列
declare
a int ;
begin
a:=1;
while a<10 loop
dbms_output.put_line(a);
a:=a+1;
end loop;
end;
for循环语句
注意:
for循环需要指定一个数字范围,以确切指定要循环多少次
for loop_variable in [revers] lower..upper
loop
执行体;
end loop;
loop_variable :循环变量,该变量不需要事先创建,作用域仅限于循环内部。只可以在循环内部使用或修改变量的值
in:为loop_variable 指定取值范围
revers:表示逆向,实际就是让loop_variable 从取值范围中逆向取值。指定在每一次循环中loop_variable 的值递减,如果不使用该选项,每一次循环中loop_variable 的值递增
lower..upper :表示取值范围。lower为取值下限,upper 为取值上限。双点号(..)为PL/SQL的取值范围符号。如果没有使用revers关键字,loop_variable 的初始默认值为lower,每循环一次loop_variable 值加1。
案列
declare
a int ;
begin
a:=1;
for a in 1..10 loop
dbms_output.put_line(a);
end loop;
end;
用for循环将表数据存入记录表中
declare
type stu is record(
age student.sage%type,
name student.sname%type
);
type array is table of stu index by binary_integer;
arr array;
m int:=1;
begin
for i in (select sage,sname from student) loop
arr(m):=i;
m:=m+1;
end loop;
for i in arr.first()..arr.last() loop
dbms_output.put_line(arr(i).age||’———-‘||arr(i).name);
end loop;
end;