PL/SQL

Hands On No. 7 : Working with Cursor in PL/SQL

About Cursor

A cursor is a type of pointer that is built into PL/SQL for querying the database, retrieving a set of records (a result set), and enabling the developer to access these records one row at a time. A cursor is a handle or a name for a private in-memory SQL area that holds a parsed statement and related information. Oracle Database implicitly manages cursors. However, there are a few interfaces that enable you to use cursors explicitly, as a named resource within a program to more effectively parse embedded SQL statements. The two main types of cursors are therefore defined as:
Implicit cursors can be used in PL/SQL without explicit code to process the cursor itself. A result set that is returned by the cursors can be used programmatically, but there is no programmatic control over the cursor itself.
Explicit cursors allow you to programmatically manage the cursor, and give you a detailed level of control over record access in the result set.

About Explicit Cursor

The implicit cursor, such as in a FOR...LOOP, are generally more efficient than an explicit cursor. However, explicit cursors may be more appropriate for your program, and they also allow you to manage specific in-memory areas as a named resource.

An explicit cursor must be defined as a variable of the same type as the columns it fetches; the data type of the record is derived from the cursor definition. Explicit cursors must be opened and may then retrieve rows within a LOOP...EXIT WHEN structure and then closed. The general form for using cursors follows:

DECLARE
  CURSOR cursor_name type IS query_definition;
OPEN cursor_name
  LOOP
    FETCH record;
    EXIT WHEN cursor_name%NOTFOUND;
    ...;             -- process fetched row
  END LOOP;
CLOSE cursor_name;

Simple Cursor Example: The below cursor fetches data from the table : expenses :

DECLARE  
  c_id expenses.eid%type; 
  c_name expenses.ename%type;  
  CURSOR cdetails IS  
      SELECT eid, ename FROM expenses;  
BEGIN  
   OPEN cdetails;  
   LOOP  
   FETCH cdetails into c_id, c_name;  
      EXIT WHEN cdetails%notfound;  
      dbms_output.put_line(c_name || ' having id ' || c_id);  
   END LOOP;  
   CLOSE cdetails; 
 
END;

Table Schema: The below command creates table : expenses

create table expenses (  
    eid number,  
    ename varchar2(40)  
)

The below command inserts records into table : expenses

INSERT INTO expenses(eid, ename) VALUES(1, 'Gardener')
INSERT INTO expenses(eid, ename) VALUES(2, 'Security')
INSERT INTO expenses(eid, ename) VALUES(3, 'Electrician')