Cursor in PL/SQL
In this tutorial we will learn Cursor in PL/SQL which is nothing but a pointer to the work area or context area of oracle engine.
A cursor is a pointer to the work area or context area, used by the oracle engine for executing SQL statements. Such a work area is privately used for SQL operations by the oracle engine.
When the oracle engine executes an SQL statements, the row of data returned is stored in cursor and is called active data set. And the cursor occupies memory size required to hold the number of rows in the active dataset.
Cursor containing the values retrieved from a table are opened in the predefined area of the main memory by oracle engine. This data is then transferred to the client machine via network.
Types of Cursor in PL/SQL
Cursor can be divided into two types based on the condition under which they are created and used:
-
Implicit Cursor
-
Explicit Cursor
Implicit Cursor
The cursor which is automatically created, maintained and closed by the Oracle engine while execution of any DML(Data Manipulation Language) queries like INSERT
, UPDATE
or DELETE
are called Implicit Cursor.
Implicit Cursors are controlled by Oracle and programmers cannot access its information.
When a DML statement is executed an implicit cursor is created and attached to it.
Explicit Cursor
The cursor which has to be created, maintained and closed by a program through PL/SQL code for the execution of any SELECT
query that returns more than one row is called Explicit Cursor.
It is a user-defined cursor declared in the Declare
section of PL/SQL block and is used in its Executable section.
Using Explicit Cursor
To define a cursor, one need to follow the following steps:
-
DECLARE the Cursor
It is done in the Declare section of the PL/SQL code by writing SQL statement that retrieves data for processing.
Syntax:
CURSOR <cursor_name> IS <SELECT query>;
For example, if we have users table with columns id,name and email, then for executing a SELECT
query this is how we can declare a cursor:
CURSOR c_users IS
SELECT id, name, email FROM users;
-
OPEN the Cursor
It is done in the Begin section of the PL/SQL code. By opening the cursor, the cursor is allocated the memory for fetching records.
Syntax:
OPEN <cursor_name>;
For the c_users
cursor declared above, it will be:
OPEN c_users;
-
FETCH the Cursor
To fetch the data from the cursor one row at a time into memory variables we use the FETCH
command.
Syntax:
fetch <cursor_name> into <list_of_variables>;
-
To check whether the cursor is open or not we use the %ISOPEN
attribute of the cursor.
Syntax:
if <cursor_name> %ISOPEN
- To determine whether fetch was successful or not. This can be done by using
FOUND
or NOT FOUND
attributes because if fetch command fails to retrieve any row from cursor then it sets found as false and not found as true.
- For processing the data held in the memory variables we need a loop(We will come to this in a short while).
- Use the Exit statement to exit from the loop after the processing is complete.
- Then, to Close the cursor, use the
CLOSE
command.
Syntax:
CLOSE cursorname;
Cursor Arributes
To work with the cursor whether Implicit or Explicit cursor, there are following attributes which are used:
ATTRIBUTE NAME |
DESCRIPTION |
%ISOPEN
|
If cursor is open it returns a Boolean value TRUE otherwise it returns Boolean value FALSE |
%FOUND |
If records fetched by cursor was successful it returns Boolean value TRUE otherwise it returns Boolean value FALSE |
%NOTFOUND |
If records fetched by cursor was unsuccessful it returns Boolean value TRUE otherwise it returns Boolean value FALSE |
%ROWCOUNT |
It returns the number of rows affected by PL/SQL statement |
Time for an Example!
Finally, let's see a cursor in action. Below we have a student table with 4 columns namely, ROLLNO, SNAME, AGE, COURSE.
ROLLNO |
SNAME |
AGE | COURSE |
11 |
Anu |
20 |
BSC |
12 |
Asha |
21 |
BCOM |
13 |
Arpit |
18 |
BCA |
14 |
Chetan |
20 |
BCA |
15 |
Nihal |
19 |
BBA |
Above table student will be used in following program, where we will use the SELECT
query to fetch the names of all the students, store them in a cursor and then loop around the cursor to print the names.
DECLARE
CURSOR student_cursor IS SELECT sname FROM Student ;
snm Student.sname %type;
BEGIN
OPEN student_cursor;
IF student_cursor%ISOPEN FALSE then
dbms_output.put_line('Cannot open cursor');
ELSE
LOOP
FETCH student_cursor INTO snm;
IF student_cursor%NOTFOUND then
Exit;
END IF;
dbms_ output.put_line('' ||snm);
END LOOP;
dbms_output.put_line('Total Records: ' ||student_cursor%rowcount);
CLOSE student_cursor;
END;
Anu
Asha
Arpit
Chetan
Nihal
Total Record: 5
PL/SQL procedure successfully completed.
In the above program,
-
We used a cursor named as
student_cursor
.
- The output shows the names of students with the total number of records found.
Cursor FOR LOOP
A Cursor FOR LOOP
is a loop meant for the cursor which automatically checks for the row count and exits the loop when all the data stored in the cursor is iterated. A cursor FOR loop automatically does the following:
- Implicitly declares its loop index as a
%rowtype
record
- Opens the cursor
- Retrieves the record from the cursor for each iteration
- Closes the cursor after processing all the records.
- A cursor can also be closed by using
EXIT
or GOTO
statements.
Syntax:
FOR variable_name IN cursor_name LOOP
-- Executable statements
END LOOP;
Examples showing use of CURSOR FOR LOOP
Below we have a simple PL/SQL code block showing the use of Cursor For Loop:
DECLARE
CURSOR student_cursor IS SELECT sname FROM Student;
BEGIN
FOR snm IN student_cursor LOOP
dbms_output.put_line('' || snm);
END LOOP;
END;
Anu
Asha
Arpit
Chetan
Nihal
PL/SQL procedure successfully completed.
In the above program,
- The cursor named as
student_cursor
is used.
- The output shows the name of students.
What is Parameterized Cursor?
A parameterized cursor is a cursor with arguments and it allows us to create dynamic SQL queries with conditions containing the variables.
Here we have the syntax for declaration of Parameterized Cursor:
CURSOR cursor_name (variable_name Datatype) IS <SELECT statement...>;
After declaring a parameterized cursor, when we open it we have to provide the value to be used in the parameterized cursor, like this:
OPEN cursor_name(value/variable/expression);
Let's take an example to demonstrate the use of Parameterized Cursors:
set serveroutput on;
DECLARE
CURSOR showRec(sno student.rollno%type) IS SELECT sname, course FROM student WHERE rollno=sno;
a student.sname%type;
b student.course%type;
c student.rollno%type;
BEGIN
d := &rollno;
OPEN showRec(d);
IF showRec%Isopen = FALSE then
dbms_output.put_line('Cannot open Cursor');
ELSE
LOOP
FETCH showRec into a,b;
EXIT WHEN showRec%NOTFOUND;
dbms_output.put_line(a|| '' ||b);
END LOOP;
End IF;
CLOSE showRec;
END;
Enter the value for d:12
--------------------
| SNAME | COURSE |
====================
| Asha | BCOM |
--------------------
PL/SQL procedure successfully completed.
In the above program,
- The cursor named as
student_cursor
is used.
- The output shows the name and course of student whose rollno is entered by the user during execution of the program.