处理程序PL / SQL上的异常

时间:2017-04-18 12:34:59

标签: exception plsql procedures

您好我想处理我的程序上的异常,以使其更有用。

我的程序添加occupations并且wage此处为表格

CREATE TABLE Occupations(
id_oc NUMBER(2),
Name_oc VARCHAR2(20) CONSTRAINT OC_name_cc NOT NULL ,
Min_wage NUMBER(7,2) CONSTRAINT OC_min_wg NOT NULL CHECK(Min_wage>100),
CONSTRAINT Oc_id_pk PRIMARY KEY (id_oc),
CONSTRAINT OC_na UNIQUE (Name_oc)
);

以下是程序

create or replace procedure zad_2a(name varchar2, min_wage number)
  is
  isFound occupations.name_oc%TYPE;
  cursor c1
  is
  select name_oc from occupations where name_oc = name;
  begin
    open c1;
    fetch c1 into isFound;
    if c1%found then dbms_output.put_line('Occupation already exists');
    else insert into occupations values(Seq_Occupations.NEXTVAL, name, min_wage);
    end if;
    close c1;
  end;
  /

此程序应具有以下例外情况:

  • 当我设定的工资少于100且超过5000
  • 虽然我添加了错误的职业名称 - 使用数字而不是字符
  • 处理其他未发现的错误

怎么做?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作并根据您的要求进行修改。

CREATE OR REPLACE PROCEDURE zad_2a (ename VARCHAR2, min_wage NUMBER)
IS
   isfound              occupations.name_oc%TYPE;
   e_custom_exception   EXCEPTION;
   PRAGMA EXCEPTION_INIT (e_custom_exception, -20001);
   l_count_int          NUMBER;

   CURSOR c1
   IS
      SELECT name_oc
        FROM occupations
       WHERE name_oc = ename;
BEGIN
   IF (min_wage < 100 OR min_wage > 5000)
   THEN
      RAISE e_custom_exception;
   END IF;

   SELECT COUNT (*)
     INTO l_count_int
     FROM DUAL
    WHERE REGEXP_LIKE (ename, '[[:digit:]]');

   IF (l_count_int > 0)
   THEN
      RAISE e_custom_exception;
   END IF;

   OPEN c1;

   FETCH c1 INTO isfound;

   IF c1%FOUND
   THEN
      DBMS_OUTPUT.put_line ('Occupation already exists');
   ELSE
      INSERT INTO occupations
           VALUES (Seq_Occupations.NEXTVAL, ename, min_wage);
   END IF;

   CLOSE c1;
EXCEPTION
   WHEN e_custom_exception
   THEN
      DBMS_OUTPUT.put_line (SQLERRM);
   WHEN OTHERS
   THEN
      RAISE;
END;
/