plsql学习:loop使用

本文深入探讨了SQL中的循环语句及其条件退出机制,通过具体例子展示了使用`loop`, `exit`, `when`等关键字进行循环控制的方法,并详细解释了`for`循环的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

------example 1: loops with IF statement-----------
set serveroutput on
declare
v_counter binary_integer := 0;
begin
loop
--increment loop counter by one
v_counter := v_counter + 1;
DBMS_OUTPUT.put_line('v_counter = '||v_counter);

--if exit condition yields true exit the loop
if v_counter = 5 then -- the same as : exit when v_counter = 5;
exit;
end if;

end loop;
--control resumes here
dbms_output.put_line('Done...');
end;

------example 2: loops with EXIT WHEN conditions-----------
set serveroutput on
declare
v_course course.courser_no%type :430;
v_instructor_id instructor.instructor_id%type :102;
v_sec_num section.section_no%type :=0;
begin
loop
--increment section number by one
v_sec_num := v_sec_num + 1;
insert into section
(section_no,course_no,section_no,instructor_id,
created_date, created_by,modified_date,
modified_by)
values
(section_id_seq.nextval,v_course,v_sec_num,
v_instructor_id,SYSDATE,USER,sysdate,user);
--if number of section added is four exit the loop
exit when v_sec_num = 4;
end loop;

--control resumes here
commit;
end;

--------exiample 3: loops with WHILE Loops condition---------
set serveroutput on
declare
c_counter binary_integer := 1;
v_sum number :=0;
begin
while v_counter <= 10 loop
v_sum := v_sum + v_counter;
dbms_output.put_line('current sum is: '||v_sum);

-- increment loop counter by one
v_counter := v_counter + 1;
end loop;

-- control resumes here
dbms_output.put_line('the sum of integers between 1 '||
'and 10 is: '||v_sum);
end;

---------example 4: loop with For Loops----------
set serveroutput on
declare
v_factorial number := 1;
begin
--the loop counter is defined implicitly by the loop
--Therefore,before the loop ,the loop counter is undefined and has no value;
for v_counter in 1..10 loop
v_factorial := v_factorial * v_counter;
end loop;

--countrol resume here
dbms_output.put_line('factorial of ten is :'||v_factorial);
end;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值