当我们在调用select语句给变量赋值时,如果有多个值存在,则会有too_many_rows错误,如果没有数据被检索到,会发生no_data_found错误。
在pl/sql中,exception关键字,用来捕获错误,类似于java中的try{}catch语句块。
too_many_rows错误:
declare
v_temp number(4);
begin
select empno into v_temp from emp where deptno=10;
exception
when too_many_rows then
dbms_output.put_line('太多记录了');
when others then
dbms_output.put_line('error');
end;
no_data_found错误:
declare
v_temp number(4);
begin
select empno into v_temp from emp where empno=2222;
exception
when no_data_found then
dbms_output.put_line('没数据');
end;
其实我们可以利用SQLCODE和SQLERRM这两个变量的值,来知道发生错误的信息。例如我们可以建立一张表,来存储我们数据库中发生的错误。
create table errorlog(
id number primary key,
errcode number,
errmsg varchar2(1024),
errdate date
);
pl/sql操作时:
declare
v_deptno dept.deptno%type:=10;
v_errcode number;
v_errmsg varchar2(1024);
begin
delete from dept where deptno=v_deptno;
commit;
exception
when others then
rollback;
v_errcode:=SQLCODE;--出错代码
v_errmsg:=SQLERRM;--出错信息
insert into errorlog values(seq_errorlog_id.nextval,v_errcode,v_errmsg,sysdate);
commit;
end;
这样我们就可以记录数据库中发生的错误了。