異常

--預約義異常
select * from emp
--未進行異常處理
declare
v_ename emp.ename%TYPE;
begin
select ename into v_ename
from emp
where empno=1234;
dbms_output.put_line('僱員名:'||v_ename);
end;sql

--進行異常處理
declare
v_ename emp.ename%TYPE;
begin
select ename into v_ename
from emp
where empno=1234;
dbms_output.put_line('僱員名:'||v_ename);
exception
when no_data_found then
dbms_output.put_line('僱員號不正確');
when TOO_MANY_ROWS then
dbms_output.put_line('查詢只能返回單行');
when OTHERS then
dbms_output.put_line('錯誤號'||sqlcode||'錯誤描述'||sqlerrm);
end;oracle

----------------------------------------------------------------------------------------------------------------------------------------
--非預約義異常code

select * from emp
select * from dept
--需求修改編號爲7788的僱員的部門編號爲99it

--在deot和emp表中創建主外鍵關係
alter table emp
add constraint pk_empno primary key(empno);
alter table dept
add constraint pk_deptno primary key(deptno);
alter table emp
add constraint fk_deptno foreign key(deptno) references dept(deptno);

declare
e_interity exception;
pragma exception_init(e_interity,-2291);-- -2291爲oracle定義的錯誤號 違背了主外健約束
begin
update emp set deptno=99 where empno=7788;
exception
when e_interity then
dbms_output.put_line('該部門不存在');
end;

--------------------------------------------------------------------------------------------------------------------------------
--自定義異常
--查詢編號爲7788僱員的補助爲例
declare
v_comm emp.comm%TYPE;
e_comm_is_null exception; --定義異常類型變量
begin
select comm into v_comm from emp where empno=7788;
if v_comm is null then
raise e_comm_is_null;
end if;
exception
when no_data_found then
dbms_output.put_line('僱員不存在!錯誤爲:'||sqlcode||sqlerrm);
when e_comm_is_null then
dbms_output.put_line('僱員無補助');
when OTHERS then
dbms_output.put_line('其餘異常');
end;io

相關文章
相關標籤/搜索