Oracle資料庫 異常處理

2022-02-02 03:25:46 字數 3133 閱讀 2100

oracle異常處理

在pl/sql語句書寫時,需要處理的異常

-- 不做異常處理時

declare

v_name emp.ename%type;

v_sal emp.sal%type;

begin

select ename,sal

into v_name,v_sal

from emp

where empno = &no;

if v_sal <3000 then

dbms_output.put_line(v_name||'的工資是:'||v_sal);

end if;

end;

在不做異常處理的時候,在輸入員工編號的值的時候,如果在資料庫中沒有,就會報錯

select * from emp;

--7369(empno) <3000(sal)

--7839 (empno) >3000

--oracle的異常處理

declare

v_name emp.ename%type;

v_sal emp.sal%type;

begin

select ename,sal

into v_name,v_sal

from emp

where empno = &no;

if v_sal <3000 then

dbms_output.put_line(v_name||'的工資是:'||v_sal);

end if;

exception

when no_data_found then

dbms_output.put_line('員工號輸入錯誤!');

when others then

dbms_output.put_line('其他錯誤!');

end;

--預定義異常處理

declare

v_name emp.ename%type;

v_sal emp.sal%type:=&salary;

begin

select ename into v_name from emp where sal = v_sal;

dbms_output.put_line(v_name||'的工資是:'||v_sal);

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('其他異常');

end;

select * from emp;

--800(sal), 乙個員工

--1250 多個員工

--8000 0個員工

--獲取異常的錯誤**和錯誤資訊

begin

delete from dept where deptno = &deptno;

exception

when others then

dbms_output.put_line(sqlcode||'####'||sqlerrm);

end;

--非預定義異常的處理

declare

--1:定義非預定義異常的識別符號

e_fk exception;

--2:將定義好的異常與oracle錯誤建立關聯

-- -2292錯誤**

pragma exception_init(e_fk,-2292);

begin

delete from dept where deptno = &deptno;

exception

--3:捕獲並處理異常

when e_fk then

dbms_output.put_line('此部門下有員工,不能刪除此部門!');

when others then

dbms_output.put_line(sqlcode||'####'||sqlerrm);

end;

--自定義異常

declare

v_empno emp.empno%type:=&empno;

--1:定義異常

e_no_result exception;

begin

update emp set sal = sal + 100 where empno = v_empno;

if sql%notfound then

--2:指定觸發異常的時機

raise e_no_result;

else

commit;

end if;

exception

--3:捕捉並處理異常

when e_no_result then

dbms_output.put_line('資料更新失敗!');

when others then

dbms_output.put_line('其他錯誤');

end;

--異常處理函式sqlcode和sqlerrm的使用

declare

v_empno emp.empno%type:= &empno;

v_ename emp.ename%type:= '&ename';

v_deptno emp.deptno%type:= &deptno;

begin

insert into emp(empno,ename,deptno)values(v_empno,v_ename,v_deptno);

if sql%found then

dbms_output.put_line('資料插入成功!');

commit;

end if;

exception

when others then

dbms_output.put_line('錯誤號:'||sqlcode);

dbms_output.put_line('錯誤資訊:'||sqlerrm);

end;

Oracle資料庫的異常處理

一 說明 oracle資料庫底冊定義了很多異常,每個異常都有乙個唯一的編碼,這些異常之中,有一些是常見的,oracle給這些異常定義了名稱,可以直接使用,其他沒有名稱直郵編碼的不能直接使用。二 分類 1 預定義異常 既有編碼又有名稱的異常是預定義異常,此類異常可以直接使用 2 非預定義異常 有編碼但...

Oracle資料庫之PL SQL異常處理

異常指的是在程式執行過程中發生的異常事件,通常是由硬體問題或者程式設計問題所導致的。pl sql程式設計過程中,即使是寫得最好的程式也可能會遇到錯誤或未預料到的事件。乙個健壯的程式都應該能夠正確處理各種異常情況,並盡可能從中恢復。1.異常處理 異常處理是用來處理正常執行過程中未預料的事件。pl sq...

資料庫 異常處理

處理步驟 declare 宣告變數 begin 處理邏輯 exception 處理異常 when 異常1 then when 異常2 then when others then 處理其他異常 end 常見異常 zero divide 除零異常 value error 型別轉換異常 too many ...