Oracle PL/SQL - %NOTFOUND Attribute: Has No Row Been Fetched?

Introduction

%NOTFOUND returns the following values:

  • NULL after the explicit cursor is opened but before the first fetch
  • FALSE if the most recent fetch from the explicit cursor returned a row
  • TRUE otherwise

You can use %NOTFOUND for exiting a loop when FETCH fails to return a row.

Demo

SQL>
SQL> drop table emp;

Table dropped.--  w  w  w  .j  a  v  a 2 s  . c o m

SQL> CREATE TABLE emp(
  2  empid NUMBER(6),
  3  first_name VARCHAR2(20),
  4  last_name VARCHAR2(25),
  5  email VARCHAR2(25),
  6  phone_number VARCHAR2(20),
  7  hire_date DATE,
  8  job_id VARCHAR2(10),
  9  salary NUMBER(8,2),
 10  commission_pct NUMBER(2,2),
 11  manager_id NUMBER(6),
 12  department_id NUMBER(4)) ;
SQL>
SQL> INSERT INTO emp VALUES( 100, 'Steven', 'King', 'SKING', '123.123.4567', TO_DATE('17-JUN-2000', 'dd-MON-yyyy'), 'CODER', 24000, NULL, NULL, 10);
SQL> INSERT INTO emp VALUES( 200, 'Joe', 'Lee', 'abc', '123.123.9999', TO_DATE('17-JUN-2010', 'dd-MON-yyyy'), 'TESTER', 25000, NULL, NULL, 20);
SQL>
SQL>
SQL> DECLARE
  2    CURSOR c1 IS
  3      SELECT last_name, salary FROM emp;
  4
  5     my_ename   emp.last_name%TYPE;
  6     my_salary  emp.salary%TYPE;
  7  BEGIN
  8    OPEN c1;
  9    LOOP
 10      FETCH c1 INTO my_ename, my_salary;
 11      IF c1%NOTFOUND THEN -- fetch failed
 12        EXIT;
 13      ELSE  -- fetch succeeded
 14        DBMS_OUTPUT.PUT_LINE
 15          ('Name = ' || my_ename || ', salary = ' || my_salary);
 16      END IF;
 17    END LOOP;
 18  END;
 19  /
Name = King, salary = 24000
Name = Lee, salary = 25000

PL/SQL procedure successfully completed.

SQL>

Related Topic