常在循环体中看到下面3种语句:
return
exit
continue
举例说明
啥都没有
-- none
begin
for i in 1 .. 10 loop
if i < 5 then
dbms_output.put_line('i < 5, i = ' || to_char(i));
else
dbms_output.put_line('i >= 5, i = ' || to_char(i));
end if;
end loop;
dbms_output.put_line('最外层');
end;
-- 输出
i < 5, i = 1
i < 5, i = 2
i < 5, i = 3
i < 5, i = 4
i >= 5, i = 5
i >= 5, i = 6
i >= 5, i = 7
i >= 5, i = 8
i >= 5, i = 9
i >= 5, i = 10
最外层
使用return
-- return
begin
for i in 1 .. 10 loop
if i < 5 then
dbms_output.put_line('i < 5, i = ' || to_char(i));
else
return; -- return
dbms_output.put_line('i >= 5, i = ' || to_char(i));
end if;
end loop;
dbms_output.put_line('最外层');
end;
-- 输出
i < 5, i = 1
i < 5, i = 2
i < 5, i = 3
i < 5, i = 4
可以看出
return
的作用是直接返回了,直接结束了整个最外层语句块begin & end
/函数/存储过程.
使用exit
-- exit
begin
for i in 1 .. 10 loop
if i < 5 then
dbms_output.put_line('i < 5, i = ' || to_char(i));
else
exit; -- exit
dbms_output.put_line('i >= 5, i = ' || to_char(i));
end if;
end loop;
dbms_output.put_line('最外层');
end;
i < 5, i = 1
i < 5, i = 2
i < 5, i = 3
i < 5, i = 4
最外层
可以看出
exit
的作用是跳出当前整个循环体,不再执行接下来的循环,同c#/java
等编程语言中的break
.
使用continue
-- continue
begin
for i in 1 .. 10 loop
if i < 5 then
dbms_output.put_line('i < 5, i = ' || to_char(i));
else
dbms_output.put_line('before continue i >= 5, i = ' || to_char(i));
continue; -- continue
dbms_output.put_line('after continue i >= 5, i = ' || to_char(i));
end if;
end loop;
dbms_output.put_line('最外层');
end;
-- 输出
i < 5, i = 1
i < 5, i = 2
i < 5, i = 3
i < 5, i = 4
before continue i >= 5, i = 5
before continue i >= 5, i = 6
before continue i >= 5, i = 7
before continue i >= 5, i = 8
before continue i >= 5, i = 9
before continue i >= 5, i = 10
最外层
可以看出
continue
是跳过/不执行本次循环,会直接进行下一次循环.