
在使用select into 为变量赋值时,如果变量是集合类型,不会产生异常,而如果是基本类型或记录类型,则会报异常。
异常产生了怎么办?当然是捕获并处理啦。
对于普通的代码块来说,在代码块的结尾处理就可以了。
但是在循环里面呢?根据异常的传播,产生异常程序会中止。但如果想要在发生异常后,达到continue的效果,可不能在结尾的exception那里添加when others then continue;的语句,否则报错。
要达到在循环中,找不到数据就continue,可以在赋值时,no_data_found的情况下作异常处理。即是让赋值语句包含在begin exception end的结构中。
另外,记录类型不能被整体判断为空,可以修改某列的值来判断,或者使用一个标志变量判断。
下面是一个小例子,我们一起感受一下。
declare
v_test2 studentRecord;--遍历游标
v_test3 studentRecord;--每次取出的记录
cursor c_test is
select *
from student_head h
where h.student_key in (3285, 3286, 3287, 3288);
flag boolean;
begin
open c_test;
loop
fetch c_test into v_test2;
exit when c_test%notfound;
flag := true;
begin
select *
into v_test3
from student_head
where student_key = v_test2.student_key
and student_status <> 'CNX';
exception
when no_data_found then--select into 没有数据时,如果是集合类型不会产生异常,记录类型报异常
flag := false;
end;
/*if v_test3 is null*/--记录类型不能整体判断为空
if flag then--判断是否有找到数据
dbms_output.put_line(v_test3.student_key || ' ' || v_test3.student_no);
end if;
end loop;
close c_test;
/*exception
when no_data_found then continue ;*/ -- 不能在异常中使用continue
-- 如果在此处理异常,会导致循环中止,要达到continue的效果,可在每次赋值进行异常处理
end;