我们知道在pl/sql中要想从数据表中向变量赋值,需要使用select into 子句。
但是它会带动来一些问题,如果查询没有记录时,会抛出no_data_found异常。
如果有多条记录时,会抛出too_many_rows异常。
这个是比较糟糕的。一旦抛出了异常,就会让过程中断。特别是no_data_found这种异常,没有严重到要让程序中断的地步,可以完全交给由程序进行处理。
CREATE OR REPLACE PROCEDURE procexception (
p varchar2
)
AS
v_postype varchar2(20);
BEGIN
SELECT pos_type
INTO v_postype
FROM pos_type_tb1
WHERE 1 = 0;--绝壁为空,报no_data_found的错误
dbms_output.put_line(v_postype);
END;
1. 直接加上异常处理。
CREATE OR REPLACE PROCEDURE procexception (
p varchar2
)
AS
v_postype varchar2(20);
BEGIN
SELECT pos_type
INTO v_postype
FROM pos_type_tb1
WHERE 1 = 0;
dbms_output.put_line(v_postype);
EXCEPTION
WHEN no_data_found THEN dbms_output.put_line("未找到数据");
程序一就会被中断
2. select into做为一个独立的块,在这个块中进行异常处理
create or replace procedure procexception(
p varchar2
) as
v_postype varchar2(20);
begin
select pos_type into v_postype from pos_type_tb1 where 1=0;--绝壁为空
dbms_output.put_line(v_postype);
--其实吧,我觉得和上面那种差不多,原理一样的呀,no zuo nod ie
exception
when no_data_found then
v_postype := '';
end;
dbms_output.put_line(v_postype);
end;
这是一种比较好的处理方式了。不会因为这个异常而引起程序中断。
3.使用游标
create or replace procedure proceexception(
p varchar2
) as
v_postype varchar2(20);
cursor c_postype is select pos_type from pos_type_tb1 where 1=0;
beign
open c_postype;
fetch c_postype into v_postype;
close c_postype;
dbms_output.put_line(v_postype);
end;
--个人觉得这样先进行非空判断会更好
create or replace procedure proceexception(
p varchar2
) as
v_postype varchar2(20);
cursor c_postype is select pos_type from pos_type_tb1 where 1=0;
beign
if c_postype%found then
open c_postype;
fetch c_postype into v_postype;
close c_postype;
dbms_output.put_line(v_postype);
end if;
end;
这样就完全的避免了no_data_found异常。完全交由程序员来进行控制了。
第二种情况是too_many_rows 异常的问题。
Too_many_rows 这个问题比起no_data_found要复杂一些。
给一个变量赋值时,但是查询结果有多个记录。
处理这种问题也有两种情况:
1. 多条数据是可以接受的,也就是说从结果集中随便取一个值就行。这种情况应该很极端了吧,如果出现这种情况,也说明了程序的严谨性存在问题。
2. 多条数据是不可以被接受的,在这种情况肯定是程序的逻辑出了问题,也说是说原来根本就不会想到它会产生多条记录。
对于第一种情况,就必须采用游标来处理,而对于第二种情况就必须使用内部块来处理,重新抛出异常。
多条数据可以接受,随便取一条,这个跟no_data_found的处理方式一样,使用游标。
我这里仅说第二种情况,不可接受多条数据,但是不要忘了处理no_data_found哦。这就不能使用游标了,必须使用内部块。
create or replace proceduer procexception2(
p varchar2
) as
v_postype varchar2(20);
begin
begin
select pos_type into v_postype from pos_type_tb1 where rownum < 5;
exception
when no_data_found then
v_postype := null;
when too_many_rows then
raise_application_error(-20000,'对v_postype赋值是,找到多条数据');
end;
dbms_output.put_line(v_postype);
end;
需要注意的是一定要加上对no_data_found的处理,对出现多条记录的情况则继续抛出异常,让上一层来处理。
总之对于select into的语句需要注意这两种情况了。需要妥当处理啊。