Oracle

[Oracle] days19 - PL/SQL 블록 내에서 에러처리

애플쩀 2022. 4. 28. 10:47

미리 정의된 에러 처리방법

오라클에서 제공하는 예측하여 정의한 오류 목록은 다음과 같다.

 

항목 에러 코드 설명

NO_DATE_FOUND ORA-01403 SQL문에 의한 검색조건을 만족하는 결과가 전혀 없는 조건의 경우
NOT_LOGGED_ON ORA-01012 데이터베이스에 연결되지 않은 상태에서 SQL문 실행하려는 경우
TOO_MANY_ROWS ORA-01422 SQL문의 실행결과가 여러 개의 행을 반환하는 경우, 스칼라 변수에 저장하려고 할 때 발생
VALUE_ERROR ORA-06502 PL/SQL 블럭 내에 정의된 변수의 길이보다 큰 값을 저장하는 경우
ZERO_DEVIDE ORA-01476 SQL문의 실행에서 컬럼의 값을 0으로 나누는 경우에 발생
INVALID_CURSOR ORA-01001 잘못 선언된 커서에 대해 연산이 발생하는 경우
DUP_VAL_ON_INDEX ORA-00001 이미 입력되어 있는 컬럼 값을 다시 입력하려는 경우에 발생

 

예제

create or replace procedure up_insemp
(
     pempno    in emp.empno%type,
     pename     IN emp.ename%type,
     pjob      IN emp.job%type,
     pmgr     IN emp.mgr%type,
    phiredate  IN emp.hiredate%TYPE,
     psal     IN emp.sal%type,
     pcomm     IN emp.comm%type,
     pdeptno      IN emp.deptno%type
)
is
--예외객체를 생성 
   --잘못된 부서번호를 주엇다. 
   ve_invalid_deptno exception ; 
   --예외객체 지정(매핑)할때 pragma exception 절 사용
   --에러코드에는 -를 붙인다. 
   pragma exception_init( ve_invalid_deptno , -02291);
begin
    insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)
    values(pempno,pename,pjob,pmgr,phiredate,psal,pcomm,pdeptno); 
    commit;
    
    exception 
    when  ve_invalid_deptno then 
        RAISE_APPLICATION_ERROR(-20002, '> DEPTNO DEPTNO FK NOT FOUND...');
    when  others then 
        RAISE_APPLICATION_ERROR(-20004, '> query other exception found ');

end;

exec up_insemp(9999,'admin','clerk',9000,sysdate, 950, null,90);

--ORA-20002: > DEPTNO DEPTNO FK NOT FOUND...

 

 

 

create or replace procedure up_updScore
( 
--급여를 입력용으로 입력받음 
psal in emp.sal%type
)
is 
 vempcount number;
 ve_no_emp_returned exception;
 
begin 
    select count(*) into vempcount --사원의 수를 세서 변수에 담음 
    from emp 
    where sal between (psal-100) and (psal+100); --그사람의 sal이 입력받은 psal-100<sla<psal+100
    
    if vempcount=0 then
    --강제로 예외 발생  raise  사용자 예외 객체 (자바는 throw new 예외명)
        raise ve_no_emp_returned;
    else 
        dbms_output.put_line('>처리결과: ' || vempcount);
    end if;
    --예외가 발생하면 exception에 걸린다. 
exception 
        when ve_no_emp_returned then 
         RAISE_APPLICATION_ERROR(-20011, '> query emp count =0....  ');
        when others then 
          RAISE_APPLICATION_ERROR(-20012, '> query other exception found ');
end;

exec up_updscore(500);
--오류 보고 -
ORA-20011: > query emp count =0....