PL / SQL插入新记录异常处理

时间:2016-05-15 11:09:42

标签: oracle plsql

我在Oracle PL / SQL中有一个作业。我必须计算在经理下工作的最大员工数量,如果这位经理有超过7名员工在他的工作下,我必须提出一个例外,其中提供了这样的信息:

  

('经理|| manager_name ||'有最大数量的员工在他之下工作'。)

否则我必须插入一名新员工并给出消息:

  

('为经理插入了一名新员工|| manager_name)。

我已经编写了代码,但我知道有些问题。

create table temp_emp as select * from employees;

select * from temp_emp;


create or replace procedure insert_emp(mngrId IN temp_emp.manager_id%type)
IS

    ex_hugemp EXCEPTION;
    emp_counter NUMBER;
    fname temp_emp.first_name%type;

BEGIN

    SELECT COUNT(*) INTO emp_counter
      FROM temp_emp 
      WHERE temp_emp.manager_id=mngrId;

    IF emp_counter > 7 THEN
        RAISE ex_hugemp;
    ELSE

      INSERT INTO temp_emp(EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER
                          ,HIRE_DATE, JOB_ID, SALARY, COMMISSION_PCT
                          ,MANAGER_ID,DEPARTMENT_ID)
        VALUES(LENGTH(EMPLOYEE_ID)+1, 'KAY', 'HORSTMAN', NULL, NULL
              ,'28-MAY-2013', 'IT_PROG', 24000, NULL, 103, 60);
      DBMS_OUTPUT.PUT_LINE('It was inserted a new employee for the manager   '||fname);

    END IF;

EXCEPTION
  WHEN ex_hugemp THEN
      DBMS_OUTPUT.PUT_LINE('Manager '||fname||'  has maximium number of employees    working under him.');

END;
/

1 个答案:

答案 0 :(得分:-1)

您的变量fname为空。填写:

SELECT first_name
  INTO fname
  FROM temp_emp
 WHERE employee_id = mngrid;

用于插入相同的mngrid。为什么是103?

什么是

LENGTH(EMPLOYEE_ID)+1

首先:这将在string中转换employee_id,从字符串中获取长度并添加1.你真的想要这个吗?第二:你不能在values()中使用列名。创建序列(将值改为1以开始):

CREATE SEQUENCE TEMP_EMP_SEQ START WITH 1;

而不是在你的程序中使用它

temp_emp_seq.nextval

CREATE OR REPLACE PROCEDURE insert_emp (mngrid IN temp_emp.manager_id%TYPE) IS
   ex_hugemp   EXCEPTION;
   emp_counter NUMBER;
   fname       temp_emp.first_name%TYPE;
BEGIN
   SELECT first_name
     INTO fname
     FROM temp_emp
    WHERE employee_id = mngrid;

   SELECT COUNT (*)
     INTO emp_counter
     FROM temp_emp
    WHERE temp_emp.manager_id = mngrid;

   IF emp_counter > 7 THEN
      RAISE ex_hugemp;
   ELSE
      INSERT INTO temp_emp (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID)
         VALUES( temp_emp_seq.nextval,'KAY','HORSTMAN',NULL,NULL,TO_DATE('28-05-2013','dd-mm-yyyy'),'IT_PROG',24000,NULL,mngrid,10);

      DBMS_OUTPUT.put_line ('It was inserted a new employee for the manager   ' || fname);
   END IF;
EXCEPTION
   WHEN ex_hugemp THEN
      DBMS_OUTPUT.put_line ('Manager ' || fname || '  has maximium number of employees    working under him.');
END;
/