1.

What are Implicit Cursors in PL/SQL

Answer»

Implicit cursors in PL/SQL are created AUTOMATICALLY by Oracle when an SQL statement is executed. This occurs when there is no explicit cursor for the statement.

An implicit cursor is associated, when INSERT, UPDATE and DELETE is issued. The attributes include %FOUND, %ISOPEN, %NOTFOUND, etc. With the attributes, you can check which all rows got affected by the operation.

The attributes:

  • %FOUND: It returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
  • %NOTFOUND: The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.
  • %ISOPEN: It returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement.
  • %ROWCOUNT: It returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO statement.

To USE any of the above attribute, use the following syntax:

sql%attribute_name

Above, set any attribute name under “attribute_name”.

Let us consider the following table for our example:

<DEPTBUDGET> +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET| +----------+------------------+---------------+------------------+ |  1 | Finance          | NORTH | 56678      | |  2 | Marketing     | EAST |      87687 | |  3 | Operations   | WEST |      95979 | |  4 | Technical      | SOUTH |    76878 | |  5 | Accounting   | NORTHWEST| 86767      | +----------+------------------+------------------+--------------+

Now, we will update the budget of all the departments and then check what all rows got affected using the implicit cursor attribute. With that we will use other attributes as well: 

DECLARE     rows_count number(2); BEGIN   UPDATE deptbudget   SET budget = budget + 3000;   IF sql%notfound THEN      dbms_output.put_line('Nothing selected!');   ELSIF sql%found THEN      rows_count := sql%rowcount;      dbms_output.put_line( rows_count || ' rows affected! ');   END IF;   END; /    

The output: 

5 rows affected!

SINCE we updated the budget for all the departments above, therefore our table rows would look like this:

<DEPTBUDGET>  +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET| +----------+------------------+---------------+------------------+ |  1 | Finance          | NORTH | 59678      | |  2 | Marketing     | EAST |      90687 | |  3 | Operations   | WEST |      98979 | |  4 | Technical      | SOUTH |    79878 | |  5 | Accounting   | NORTHWEST| 89767      | +----------+------------------+------------------+--------------+


Discussion

No Comment Found