No_data_found异常处理

No_data_found Exception handling

PROCEDURE getEmployeeDetails(EmpID     IN NUMBER,
                             EmpSalary OUT NUMBER) Is
  BEGIN

    SELECT Salary
      into EmpSalary
      FROM Employee_accounts_master
     WHERE Emp_ID = EmpID
       AND SALARY = 'B';

  EXCEPTION
    WHEN NO_DATA_FOUND THEN

      dbms_output.put_line(-20001);

当上述查询未获取任何行时,此过程将抛出 NO_DATA_FOUND 异常。我需要做一些其他的 update/insert 过程,而不是抛出这个异常。如何实现这一目标。

只需在异常部分执行,检查以下内容:

Begin
BEGIN

        SELECT Salary
          into EmpSalary
          FROM Employee_accounts_master
         WHERE Emp_ID = EmpID
           AND SALARY = 'B';

      EXCEPTION
        WHEN NO_DATA_FOUND THEN
         -- use the label
           goto myinsert;
     end;
    -- here is your line 67 code starts
   <<myinsert>>
    -- your insert statement, for eg.
    insert into emp (empno) values (1);
 end;

测试记录是否存在是显式游标有用的一个实例。

PROCEDURE getEmployeeDetails(EmpID     IN NUMBER,
                             EmpSalary OUT NUMBER) 
IS
     cursor c_emp (p_EmpID NUMBER) is
        SELECT Salary
          FROM Employee_accounts_master 
         WHERE Emp_ID = p_EmpID
           AND SALARY = 'B';
     r_Emp c_emp%rowtype;
BEGIN
        open c_emp(EmpID);
        fetch c_emp into r_emp;
        if c_emp%NOTFOUND then
            insert into employee (emp_id) values (EmpID);
        end if;
        close c_emp;
  END;

或者,您可以使用 MERGE 语句,但只需编写一个 WHEN NOT MATCHED THEN INSERT 分支。 Find out more