SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
Oracle For Beginners

Page : 1

Chapter 18

CURSOR HANDLING
What is a cursor?
When do we need explicit cursor?
Handling explicit cursor
Cursor FOR loop
Sample program
Implicit cursor
Cursor attributes
Input arguments to cursor
FOR UPDATE and CURRENT OF clauses

What is a cursor?
Oracle uses a work area to execute SQL commands and store processing information. PL/SQL
allows you to access this area through a name using a cursor.
Cursors that you use in PL/SQL are of two types:
Implicit cursor
Explicit cursor

Implicit Cursor
PL/SQL declares an implicit cursor for every DML command, and queries that return a single
row. The name of the implicit cursor is SQL. You can directly use this cursor without any
declaration. We will see more about this later in this chapter.

Explicit Cursor
PL/SQL’s implicit cursor can handle only single-row queries. If you ever need to select more
than one row using SELECT in PL/SQL then you have to use explicit cursor.

srikanthtechnologies.com
Oracle For Beginners

Page : 2

When do we need an explicit cursor?
SELECT command in PL/SQL block can retrieve only one row. If SELECT command retrieves no
row then NO_DATA_FOUND exception will be raised. If SELECT retrieves more than one row
then TOO_MANY_ROWS exception occurs.
So, a SELECT command will succeed only when it retrieves a single row. The reason for this is;
SELECT command copies the values of columns that it retrieved into variables. If multiple rows
are retrieved then multiple values for each column are to be copied to a single variable and
that creates the problem.
declare
v_ccode
v_fee
begin

varchar2(5);
number(5);

select
ccode,fee into
from courses
where duration > 25;

v_ccode, v_fee

end;
SELECT command in the above example will raise TOO_MANY_ROWS exception if more than
one course is having duration more than 25.
An explicit cursor is the solution to the problem. A cursor can store a collection of records
retrieved by a query. Then it allows us to fetch one record from cursor at a time and thereby
enabling to process all the records in the cursor.
As you can see in figure 1, SELECT retrieves rows from database into cursor. Cursor stores the
collection of record retrieved by SELECT. Then the program can fetch one row at a time from
cursor and apply the required process to it.
SELECT command given at the time of declaring the cursor is used to retrieve the data from
database. Records in the cursor will be fetched one at a time using FETCH statement, which
fetches the data from current row of the cursor and copies the data into variables.
C u rso r

SELEC T used
w ith c u rs o r
C u rre n t R o w

FETCH

v a r ia b le s

D a ta b a s e

Figure 1: An explicit cursor.

srikanthtechnologies.com
Oracle For Beginners

Page : 3

Handling explicit cursor
Explicit cursor is a name used to refer to an area where you can place multiple rows retrieved
by SELECT. You must use an explicit cursor whenever you have to use a multi-row query in
PL/SQL.
The following are the steps required to create and use an explicit cursor:
Declare the cursor in Declare section
Open the cursor using OPEN statement in Executable part
Fetch one row at a time using FETCH statement.
Close the cursor after all the records in the cursor are fetched and processed by using
CLOSE.
The following section will discuss each step in detail.

Declaring a cursor
A cursor is declared in Declare section using CURSOR statement. At the time of declaration the
name of the cursor and the associated SELECT statement are mentioned.

CURSOR cursor_name [(parameter[, parameter]...)]
IS select_statement
[FOR UPDATE [OF column,column, . . . ];
The following example shows how to declare a cursor.
declare
cursor course_det is
select ccode, name, fee
from
courses;
begin
end;
COURSE_DET is the name of the cursor, which will be populated with the rows retrieved by the
given SELECT at the time of opening the cursor.
We will discuss more about parameters in declaration of cursor in the section “Input
Arguments”.
The following example declares a cursor that takes course code and number of batches of the
course in the ascending order of number of batches.

srikanthtechnologies.com
Oracle For Beginners

Page : 4

Opening a cursor using OPEN statement
OPEN statement is used to execute the SELECT command associated with the cursor and place
the rows retrieved by the query into cursor.

OPEN

cursor_name

[(input arguments)];

Cursor_name is the name of the cursor that is to be opened.
Input_arguments are the values to be passed to the parameters of the cursor. More on this
later in the section “Input Arguments”.
The following statement opens the cursor COURSE_DET and places the rows retrieved by the
query into the cursor.
declare
cursor course_det is
select ccode, name, fee
from
courses;
begin
open course_det;
end;

Fetching rows using FETCH statement
Once cursor is opened using OPEN statement, cursor has a set of rows, which can be fetched
using FETCH statement. FETCH statement takes the data of the current row in the cursor
and copies the values of the columns into variables given after INTO keyword.

FETCH

cursor_name INTO

variable-1, variable-2, . . .;

For each column in the cursor there should be a corresponding variable in FETCH
statement. Also make sure the data types of variables and corresponding columns are
matching.
The following snippet demonstrates how to fetch and copy data from current row of the cursor
to variables given after INTO.
declare
cursor course_det is
select ccode, name, fee
from
courses;
v_ccode
v_name
v_fee

courses.ccode%type;
courses.name%type;
courses.fee%type;

srikanthtechnologies.com
Oracle For Beginners

Page : 5

begin
open course_det;
loop
fetch course_det
. . .

into

v_ccode, v_name, v_fee;

end loop;
end;

FETCH statement is to be used inside the loop to repeatedly fetch rows from the cursor. The
process of fetching should stop once all rows of the cursor are fetch (reached end of cursor).
The following code will show how to exit cursor when cursor is completely processed.
loop
fetch
exit

course_det into v_ccode, v_name, v_fee;
when course_det%notfound;

end loop;
NOTFOUND attribute of the cursor returns TRUE when previous FETCH doesn’t successfully
read a row from cursor.
We will discuss more about attributes of explicit and implicit cursors later in his chapter.

Closing a cursor using CLOSE command
CLOSE statement is used to close cursor after the cursor is processed.
release the resources associated with cursor.

CLOSE cursor_name;
The following example closes COURSE_DET cursor:
declare
begin
open ..
loop
...
end loop;
close course_det;
end;

srikanthtechnologies.com

Closing a cursor would
Oracle For Beginners

Page : 6

Cursor For Loop
In order to process a cursor, you can use cursor FOR loop to automate the following steps.
Opening cursor
Fetching rows from the cursor
Terminating loop when all rows in the cursor are fetched
Closing cursor
The following is the syntax of cursor for loop. This for loop is specifically meant to process
cursors.

FOR rowtype_variable IN
LOOP
Statements;
END LOOP;

cursor_name

rowtype_variable is automatically declared by cursor for loop. It is of ROWTYPE of the
cursor. It has columns of the cursor as fields. These fields can be accessed using
rowtype_variable.fieldname.
The following example shows the process involved without using cursor for loop and using for
loop.
DECLARE
cursor courses_cursor
select ccode,fee
from
courses;
BEGIN
-- open cursor
open courses_cursor;

is

loop
fetch courses_cursor into v_ccode, v_fee;
-- if previous fetch failed then exit loop
-- NOTFOUND attribute of the cursor return true if
-- previous fetch has failed.
exit when courses_cursor%notfound;
-- process the record fetched from cursor
. . .
end loop;
close
END;

courses_cursor;

srikanthtechnologies.com
Oracle For Beginners

Page : 7

The same program can also be written using cursor for loop as follows:
declare
cursor courses_cursor
is
select ccode,fee
from
courses;
begin
-- cursor is opened and one row at a time is fetched
-- loop is automatically terminated if all records are fetched
for rec in courses_cursor
loop
-- process the record fetched from cursor
if rec.fee > 5000 then
-- do something here
end if;
end loop;
end;

The following are the important steps in the above program:
Cursor COURSES_CURSOR is automatically opened by cursor for loop.
REC is declared automatically by cursor for loop as:
REC courses_cursor%ROWTYPE;
But REC is available only inside the cursor for loop. It contains the same columns as the
cursor. In order to access a column of the current row of the cursor, in the cursor for loop,
use the format:
rowtype_variable.columnname
Statements in the cursor for loop are executed once for each row of the cursor. And for
each row of the cursor, row is copied into rowtype_variable.
Loop is terminated once end of cursor is reached. And cursor is closed.

The following section will summarize what we have seen so far by showing how to write a
simple program using cursor.

srikanthtechnologies.com
Oracle For Beginners

Page : 8

Sample program
Let us now put all pieces together and write a complete program that makes use of cursor.
The sample program is to update FEE of each course based on the following table.
No. of students
> 10
> 20
Otherwise

/* Author :
Date
:
Place :
Purpose:

Percentage of change
10% increase
15% increase
5% decrease

P.Srikanth
22-10-2001
Vizag.
Sample cursor program to illustrate how to handle a cursor*/

declare
cursor courses_cursor is
select c.ccode, count(*) count
from
batches b, students s
where c.ccode = b.ccode and b.bcode = s.bcode
group by c.ccode;
v_per number(5,2);
begin
-- rec is automatically declared
for rec in courses_cursor
loop
if rec.count > 20 then
v_per:= 1.15;
elsif rec.count > 10 then
v_per := 1.10;
else
v_per := 0.90;
end if;
-- update row in the table
update courses set fee = fee * v_per
where ccode = rec.ccode;
end loop;
end;
/
The above program is used to declare a cursor that takes course code and no. of students
joined into that course using a SELECT that joins BATCHES and STUDENTS table. Depending
upon the no. of students joined into each course, it updates the course fee of the course.
It uses cursor for loop to take one row at a time from COURSES_CURSOR and updates the FEE
of COURSES table after the process.

srikanthtechnologies.com
Oracle For Beginners

Page : 9

Implicit cursor
Oracle implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor. You can refer to this cursor using the name SQL.
You cannot use the OPEN, FETCH, and CLOSE statements with SQL cursor. But, you can use
cursor attributes to get information about the most recently executed SQL statement.
The following example shows how to use implicit cursor to know whether the most recent
UPDATE has updated any rows or not.
declare
begin
update . . .
if SQL%NOTFOUND then
statements;
end if;

end;
NOTFOUND is an attribute of implicit cursor that returns true if previous UPDATE command
has not affected any row.

Cursor attributes
Cursor attributes allow you to get information regarding cursor. For example, you can get the
number of rows fetched so far from a cursor using ROWCOUNT attribute and whether a row is
fetched or not using FOUND attribute.
Use the following syntax to access cursor attributes:

cursor_name%Attribute

Explicit cursor attributes
The following is the list of available cursor attributes and their meaning for explicit cursor.
Attribute
NOTFOUND
FOUND
ROWCOUNT
ISOPEN
Table 1: Explicit

What it returns?
True, if previous fetch failed.
True, if previous fetch succeeded.
Number of rows fetched from cursor so far.
True, if cursor is currently open
Cursor Attributes.

Implicit cursor attributes
Cursor attributes do not have the same meaning for both explicit and implicit cursors. The
following table shows the meaning of cursor attributes with implicit cursor.

srikanthtechnologies.com
Oracle For Beginners

Page : 10

Attribute
NOTFOUND
FOUND
ROWCOUNT

What it returns?
True, if previous DML operation didn’t affect any row.
True, if previous DML operation affected any row.
Number of rows affected by the most recent DML
operation.
Table 2: Implicit Cursor Attributes.
The following example shows how to use ROWCOUNT attribute with implicit cursor to know
how many rows were updated with most recent UPDATE command.
begin
update courses set
fee = fee & 1.1
where duration > 25;
/*

if more than 5 rows are effected
then rollback updation */

if

SQL%ROWCOUNT
rollback;

>

5 then

else
commit;
end if;
end;
The following is how you use cursor attributes with explicit cursors. Attribute NOTFOUND
returns true if previous FETCH statement couldn’t fetch any row.
LOOP
fetch

courses_cursor into

v_ccode, v_fee;

/* exit loop if previous FETCH failed */
exit

when

students_cursor%NOTFOUND;

/* process the record fetched */
END LOOP;

In the above example EXIT is executed when NOTFOUND attribute of cursor
CORUSES_CURSOR returns TRUE.

Input arguments to cursor
Input arguments are the values that are passed to cursor at the time of opening the cursor.
These values are passed to parameters that are declared in cursor and they are used while
executing the query.
The following example will illustrate the process.
declare
cursor batch_cursor ( pccode varchar2) is
select * from batches where ccode = pccode;

srikanthtechnologies.com
Oracle For Beginners

Page : 11

begin
-- open the cursor and get all batches of course oracle.
open batch_cursor(‘ora’);
-- process the cursor
close batch_cursor;
-- open the same cursor but with a different course code
open batch_cursor(‘vb’);
-- process the cursor, which contains details of batches of vb
close batch_cursor;
end;

Cursor BATCH_CURSOR is declared to take a parameter or input argument – PCCODE. The
parameter is used to retrieve details of the batches of the given course.
At the time of opening the cursor, the value for parameter PCCODE is to be passed by
enclosing the value within parentheses. The value is passed to PCCODE, which is then used in
the query of the cursor.
The advantage of the input arguments, as you can see in the example above, is that you can
use the same cursor to represent different sets of records at different points of time. In the
above example, first cursor contains the batches of Oracle course then that cursor is closed
and reopened with course code VB to take the details of batches of VB.

In case of cursor for loop, values to input arguments are passed at the time of using cursor in
for loop as follows:
for rec in batch_cursor(‘ora’)
loop
...
end loop;

Note: The size of data type of input arguments should not be given. That means, we should
give only VARCHAR2 and not VARCHAR2 (10).

FOR UPDATE and CURRENT OF
By default, Oracle locks rows while manipulating the rows. But it is possible to override default
locking by using FOR UPDATE option of SELECT command.
FOR UPDATE option clause can be used with SELECT while declaring cursor to lock all records
retrieved by cursor to make sure they are not locked by others before we update or delete
them. As Oracle automatically locks rows for you, FOR UPDATE clause is required only when
you want to lock rows ahead of update or delete - at the time of opening cursor.

srikanthtechnologies.com
Oracle For Beginners

Page : 12

CURRENT OF clause with UPDATE and DELETE commands can be used to refer to the current
row in the cursor.
Note: FOR UPDATE must be given if you want to use CURRENT OF clause to refer to current
row in the cursor.
The following example shows how to use FOR UPDATE OF and CURRENT OF clauses:
DECLARE
CURSOR course_details IS
SELECT ccode, name, fee from courses
FOR UPDATE OF fee;
...
BEGIN
OPEN course_details;
LOOP
FETCH course_details INTO...
...
/* Update the current record in the cursor
course_details */
UPDATE courses SET fee = new_fee
WHERE CURRENT OF course_details;
END LOOP;
CLOSE

course_details;

END;

srikanthtechnologies.com
Oracle For Beginners

Page : 13

Summary
A cursor is always used by PL/SQL to execute single-row queries and DML command. But, in
order to use multi-row query, you have to use an explicit cursor. An explicit cursor contains a
row-set, which is retrieved by multi-row query. Implicit cursor is used to get information about
the most recent DML operation.
Cursor FOR loop is used to open, fetch rows until end of cursor, and close the cursor.
Input arguments of the cursor can be used to pass values to cursor at the time of opening
cursor so that these values are used by SELECT command of the cursor. FOR UPDATE clause is
used to override default locking and CURRENT OF is used to refer to current record in the
cursor.

Exercises
1. Which attribute is used to find out how many rows were fetched from cursor so far.
2. Can we use ISOPEN attribute with implicit cursor.
3. How can we know whether the most recent DML operation has affected any row?
4. How do you declare an input arguments for the cursor and how do you pass value to it?
5. What is the use of CURRENT OF clause in DELETE and UPDATE commands?
6. Create table called COURSE_DETAILS with the columns:
Course Code, No. of batches completed, Total amount collected so far

srikanthtechnologies.com

Contenu connexe

Tendances

Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONLalitkumar_98
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaRahulAnanda1
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsqlArun Sial
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structureMAHALAKSHMI P
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries LectureFelipe Costa
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vishal Patil
 

Tendances (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Method overriding
Method overridingMethod overriding
Method overriding
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
PLSQL Cursors
PLSQL CursorsPLSQL Cursors
PLSQL Cursors
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Cursors.ppt
Cursors.pptCursors.ppt
Cursors.ppt
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Oracle: Control Structures
Oracle: Control StructuresOracle: Control Structures
Oracle: Control Structures
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 

Similaire à Oracle Cursor Handling Guide

plsql tutorialhub....
plsql tutorialhub....plsql tutorialhub....
plsql tutorialhub....Abhiram Vijay
 
Intro to tsql unit 13
Intro to tsql   unit 13Intro to tsql   unit 13
Intro to tsql unit 13Syed Asrarali
 
Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Thuan Nguyen
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-onlyAshwin Kumar
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSORArun Sial
 
Cursors in oracle
Cursors in oracleCursors in oracle
Cursors in oracleTamizhmuhil
 
Les22[1]Advanced Explicit Cursor Concepts
Les22[1]Advanced Explicit Cursor ConceptsLes22[1]Advanced Explicit Cursor Concepts
Les22[1]Advanced Explicit Cursor Conceptssiavosh kaviani
 
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Alexey Furmanov
 
Advanced plsql mock_assessment
Advanced plsql mock_assessmentAdvanced plsql mock_assessment
Advanced plsql mock_assessmentSaurabh K. Gupta
 
Basic cursors in oracle
Basic cursors in oracleBasic cursors in oracle
Basic cursors in oracleSuhel Firdus
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfacsmadurai
 

Similaire à Oracle Cursor Handling Guide (20)

plsql tutorialhub....
plsql tutorialhub....plsql tutorialhub....
plsql tutorialhub....
 
Module07
Module07Module07
Module07
 
Intro to tsql unit 13
Intro to tsql   unit 13Intro to tsql   unit 13
Intro to tsql unit 13
 
4 cursors
4 cursors4 cursors
4 cursors
 
Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSOR
 
Oracle: Cursors
Oracle: CursorsOracle: Cursors
Oracle: Cursors
 
Oracle:Cursors
Oracle:CursorsOracle:Cursors
Oracle:Cursors
 
Cursors in oracle
Cursors in oracleCursors in oracle
Cursors in oracle
 
Les22[1]Advanced Explicit Cursor Concepts
Les22[1]Advanced Explicit Cursor ConceptsLes22[1]Advanced Explicit Cursor Concepts
Les22[1]Advanced Explicit Cursor Concepts
 
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
 
Cursors
CursorsCursors
Cursors
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Advanced plsql mock_assessment
Advanced plsql mock_assessmentAdvanced plsql mock_assessment
Advanced plsql mock_assessment
 
PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
Basic cursors in oracle
Basic cursors in oracleBasic cursors in oracle
Basic cursors in oracle
 
Day 6.pptx
Day 6.pptxDay 6.pptx
Day 6.pptx
 
Task Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdfTask Perform addition subtraction division and multiplic.pdf
Task Perform addition subtraction division and multiplic.pdf
 

Dernier

4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 

Dernier (20)

4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 

Oracle Cursor Handling Guide

  • 1. Oracle For Beginners Page : 1 Chapter 18 CURSOR HANDLING What is a cursor? When do we need explicit cursor? Handling explicit cursor Cursor FOR loop Sample program Implicit cursor Cursor attributes Input arguments to cursor FOR UPDATE and CURRENT OF clauses What is a cursor? Oracle uses a work area to execute SQL commands and store processing information. PL/SQL allows you to access this area through a name using a cursor. Cursors that you use in PL/SQL are of two types: Implicit cursor Explicit cursor Implicit Cursor PL/SQL declares an implicit cursor for every DML command, and queries that return a single row. The name of the implicit cursor is SQL. You can directly use this cursor without any declaration. We will see more about this later in this chapter. Explicit Cursor PL/SQL’s implicit cursor can handle only single-row queries. If you ever need to select more than one row using SELECT in PL/SQL then you have to use explicit cursor. srikanthtechnologies.com
  • 2. Oracle For Beginners Page : 2 When do we need an explicit cursor? SELECT command in PL/SQL block can retrieve only one row. If SELECT command retrieves no row then NO_DATA_FOUND exception will be raised. If SELECT retrieves more than one row then TOO_MANY_ROWS exception occurs. So, a SELECT command will succeed only when it retrieves a single row. The reason for this is; SELECT command copies the values of columns that it retrieved into variables. If multiple rows are retrieved then multiple values for each column are to be copied to a single variable and that creates the problem. declare v_ccode v_fee begin varchar2(5); number(5); select ccode,fee into from courses where duration > 25; v_ccode, v_fee end; SELECT command in the above example will raise TOO_MANY_ROWS exception if more than one course is having duration more than 25. An explicit cursor is the solution to the problem. A cursor can store a collection of records retrieved by a query. Then it allows us to fetch one record from cursor at a time and thereby enabling to process all the records in the cursor. As you can see in figure 1, SELECT retrieves rows from database into cursor. Cursor stores the collection of record retrieved by SELECT. Then the program can fetch one row at a time from cursor and apply the required process to it. SELECT command given at the time of declaring the cursor is used to retrieve the data from database. Records in the cursor will be fetched one at a time using FETCH statement, which fetches the data from current row of the cursor and copies the data into variables. C u rso r SELEC T used w ith c u rs o r C u rre n t R o w FETCH v a r ia b le s D a ta b a s e Figure 1: An explicit cursor. srikanthtechnologies.com
  • 3. Oracle For Beginners Page : 3 Handling explicit cursor Explicit cursor is a name used to refer to an area where you can place multiple rows retrieved by SELECT. You must use an explicit cursor whenever you have to use a multi-row query in PL/SQL. The following are the steps required to create and use an explicit cursor: Declare the cursor in Declare section Open the cursor using OPEN statement in Executable part Fetch one row at a time using FETCH statement. Close the cursor after all the records in the cursor are fetched and processed by using CLOSE. The following section will discuss each step in detail. Declaring a cursor A cursor is declared in Declare section using CURSOR statement. At the time of declaration the name of the cursor and the associated SELECT statement are mentioned. CURSOR cursor_name [(parameter[, parameter]...)] IS select_statement [FOR UPDATE [OF column,column, . . . ]; The following example shows how to declare a cursor. declare cursor course_det is select ccode, name, fee from courses; begin end; COURSE_DET is the name of the cursor, which will be populated with the rows retrieved by the given SELECT at the time of opening the cursor. We will discuss more about parameters in declaration of cursor in the section “Input Arguments”. The following example declares a cursor that takes course code and number of batches of the course in the ascending order of number of batches. srikanthtechnologies.com
  • 4. Oracle For Beginners Page : 4 Opening a cursor using OPEN statement OPEN statement is used to execute the SELECT command associated with the cursor and place the rows retrieved by the query into cursor. OPEN cursor_name [(input arguments)]; Cursor_name is the name of the cursor that is to be opened. Input_arguments are the values to be passed to the parameters of the cursor. More on this later in the section “Input Arguments”. The following statement opens the cursor COURSE_DET and places the rows retrieved by the query into the cursor. declare cursor course_det is select ccode, name, fee from courses; begin open course_det; end; Fetching rows using FETCH statement Once cursor is opened using OPEN statement, cursor has a set of rows, which can be fetched using FETCH statement. FETCH statement takes the data of the current row in the cursor and copies the values of the columns into variables given after INTO keyword. FETCH cursor_name INTO variable-1, variable-2, . . .; For each column in the cursor there should be a corresponding variable in FETCH statement. Also make sure the data types of variables and corresponding columns are matching. The following snippet demonstrates how to fetch and copy data from current row of the cursor to variables given after INTO. declare cursor course_det is select ccode, name, fee from courses; v_ccode v_name v_fee courses.ccode%type; courses.name%type; courses.fee%type; srikanthtechnologies.com
  • 5. Oracle For Beginners Page : 5 begin open course_det; loop fetch course_det . . . into v_ccode, v_name, v_fee; end loop; end; FETCH statement is to be used inside the loop to repeatedly fetch rows from the cursor. The process of fetching should stop once all rows of the cursor are fetch (reached end of cursor). The following code will show how to exit cursor when cursor is completely processed. loop fetch exit course_det into v_ccode, v_name, v_fee; when course_det%notfound; end loop; NOTFOUND attribute of the cursor returns TRUE when previous FETCH doesn’t successfully read a row from cursor. We will discuss more about attributes of explicit and implicit cursors later in his chapter. Closing a cursor using CLOSE command CLOSE statement is used to close cursor after the cursor is processed. release the resources associated with cursor. CLOSE cursor_name; The following example closes COURSE_DET cursor: declare begin open .. loop ... end loop; close course_det; end; srikanthtechnologies.com Closing a cursor would
  • 6. Oracle For Beginners Page : 6 Cursor For Loop In order to process a cursor, you can use cursor FOR loop to automate the following steps. Opening cursor Fetching rows from the cursor Terminating loop when all rows in the cursor are fetched Closing cursor The following is the syntax of cursor for loop. This for loop is specifically meant to process cursors. FOR rowtype_variable IN LOOP Statements; END LOOP; cursor_name rowtype_variable is automatically declared by cursor for loop. It is of ROWTYPE of the cursor. It has columns of the cursor as fields. These fields can be accessed using rowtype_variable.fieldname. The following example shows the process involved without using cursor for loop and using for loop. DECLARE cursor courses_cursor select ccode,fee from courses; BEGIN -- open cursor open courses_cursor; is loop fetch courses_cursor into v_ccode, v_fee; -- if previous fetch failed then exit loop -- NOTFOUND attribute of the cursor return true if -- previous fetch has failed. exit when courses_cursor%notfound; -- process the record fetched from cursor . . . end loop; close END; courses_cursor; srikanthtechnologies.com
  • 7. Oracle For Beginners Page : 7 The same program can also be written using cursor for loop as follows: declare cursor courses_cursor is select ccode,fee from courses; begin -- cursor is opened and one row at a time is fetched -- loop is automatically terminated if all records are fetched for rec in courses_cursor loop -- process the record fetched from cursor if rec.fee > 5000 then -- do something here end if; end loop; end; The following are the important steps in the above program: Cursor COURSES_CURSOR is automatically opened by cursor for loop. REC is declared automatically by cursor for loop as: REC courses_cursor%ROWTYPE; But REC is available only inside the cursor for loop. It contains the same columns as the cursor. In order to access a column of the current row of the cursor, in the cursor for loop, use the format: rowtype_variable.columnname Statements in the cursor for loop are executed once for each row of the cursor. And for each row of the cursor, row is copied into rowtype_variable. Loop is terminated once end of cursor is reached. And cursor is closed. The following section will summarize what we have seen so far by showing how to write a simple program using cursor. srikanthtechnologies.com
  • 8. Oracle For Beginners Page : 8 Sample program Let us now put all pieces together and write a complete program that makes use of cursor. The sample program is to update FEE of each course based on the following table. No. of students > 10 > 20 Otherwise /* Author : Date : Place : Purpose: Percentage of change 10% increase 15% increase 5% decrease P.Srikanth 22-10-2001 Vizag. Sample cursor program to illustrate how to handle a cursor*/ declare cursor courses_cursor is select c.ccode, count(*) count from batches b, students s where c.ccode = b.ccode and b.bcode = s.bcode group by c.ccode; v_per number(5,2); begin -- rec is automatically declared for rec in courses_cursor loop if rec.count > 20 then v_per:= 1.15; elsif rec.count > 10 then v_per := 1.10; else v_per := 0.90; end if; -- update row in the table update courses set fee = fee * v_per where ccode = rec.ccode; end loop; end; / The above program is used to declare a cursor that takes course code and no. of students joined into that course using a SELECT that joins BATCHES and STUDENTS table. Depending upon the no. of students joined into each course, it updates the course fee of the course. It uses cursor for loop to take one row at a time from COURSES_CURSOR and updates the FEE of COURSES table after the process. srikanthtechnologies.com
  • 9. Oracle For Beginners Page : 9 Implicit cursor Oracle implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursor. You can refer to this cursor using the name SQL. You cannot use the OPEN, FETCH, and CLOSE statements with SQL cursor. But, you can use cursor attributes to get information about the most recently executed SQL statement. The following example shows how to use implicit cursor to know whether the most recent UPDATE has updated any rows or not. declare begin update . . . if SQL%NOTFOUND then statements; end if; end; NOTFOUND is an attribute of implicit cursor that returns true if previous UPDATE command has not affected any row. Cursor attributes Cursor attributes allow you to get information regarding cursor. For example, you can get the number of rows fetched so far from a cursor using ROWCOUNT attribute and whether a row is fetched or not using FOUND attribute. Use the following syntax to access cursor attributes: cursor_name%Attribute Explicit cursor attributes The following is the list of available cursor attributes and their meaning for explicit cursor. Attribute NOTFOUND FOUND ROWCOUNT ISOPEN Table 1: Explicit What it returns? True, if previous fetch failed. True, if previous fetch succeeded. Number of rows fetched from cursor so far. True, if cursor is currently open Cursor Attributes. Implicit cursor attributes Cursor attributes do not have the same meaning for both explicit and implicit cursors. The following table shows the meaning of cursor attributes with implicit cursor. srikanthtechnologies.com
  • 10. Oracle For Beginners Page : 10 Attribute NOTFOUND FOUND ROWCOUNT What it returns? True, if previous DML operation didn’t affect any row. True, if previous DML operation affected any row. Number of rows affected by the most recent DML operation. Table 2: Implicit Cursor Attributes. The following example shows how to use ROWCOUNT attribute with implicit cursor to know how many rows were updated with most recent UPDATE command. begin update courses set fee = fee & 1.1 where duration > 25; /* if more than 5 rows are effected then rollback updation */ if SQL%ROWCOUNT rollback; > 5 then else commit; end if; end; The following is how you use cursor attributes with explicit cursors. Attribute NOTFOUND returns true if previous FETCH statement couldn’t fetch any row. LOOP fetch courses_cursor into v_ccode, v_fee; /* exit loop if previous FETCH failed */ exit when students_cursor%NOTFOUND; /* process the record fetched */ END LOOP; In the above example EXIT is executed when NOTFOUND attribute of cursor CORUSES_CURSOR returns TRUE. Input arguments to cursor Input arguments are the values that are passed to cursor at the time of opening the cursor. These values are passed to parameters that are declared in cursor and they are used while executing the query. The following example will illustrate the process. declare cursor batch_cursor ( pccode varchar2) is select * from batches where ccode = pccode; srikanthtechnologies.com
  • 11. Oracle For Beginners Page : 11 begin -- open the cursor and get all batches of course oracle. open batch_cursor(‘ora’); -- process the cursor close batch_cursor; -- open the same cursor but with a different course code open batch_cursor(‘vb’); -- process the cursor, which contains details of batches of vb close batch_cursor; end; Cursor BATCH_CURSOR is declared to take a parameter or input argument – PCCODE. The parameter is used to retrieve details of the batches of the given course. At the time of opening the cursor, the value for parameter PCCODE is to be passed by enclosing the value within parentheses. The value is passed to PCCODE, which is then used in the query of the cursor. The advantage of the input arguments, as you can see in the example above, is that you can use the same cursor to represent different sets of records at different points of time. In the above example, first cursor contains the batches of Oracle course then that cursor is closed and reopened with course code VB to take the details of batches of VB. In case of cursor for loop, values to input arguments are passed at the time of using cursor in for loop as follows: for rec in batch_cursor(‘ora’) loop ... end loop; Note: The size of data type of input arguments should not be given. That means, we should give only VARCHAR2 and not VARCHAR2 (10). FOR UPDATE and CURRENT OF By default, Oracle locks rows while manipulating the rows. But it is possible to override default locking by using FOR UPDATE option of SELECT command. FOR UPDATE option clause can be used with SELECT while declaring cursor to lock all records retrieved by cursor to make sure they are not locked by others before we update or delete them. As Oracle automatically locks rows for you, FOR UPDATE clause is required only when you want to lock rows ahead of update or delete - at the time of opening cursor. srikanthtechnologies.com
  • 12. Oracle For Beginners Page : 12 CURRENT OF clause with UPDATE and DELETE commands can be used to refer to the current row in the cursor. Note: FOR UPDATE must be given if you want to use CURRENT OF clause to refer to current row in the cursor. The following example shows how to use FOR UPDATE OF and CURRENT OF clauses: DECLARE CURSOR course_details IS SELECT ccode, name, fee from courses FOR UPDATE OF fee; ... BEGIN OPEN course_details; LOOP FETCH course_details INTO... ... /* Update the current record in the cursor course_details */ UPDATE courses SET fee = new_fee WHERE CURRENT OF course_details; END LOOP; CLOSE course_details; END; srikanthtechnologies.com
  • 13. Oracle For Beginners Page : 13 Summary A cursor is always used by PL/SQL to execute single-row queries and DML command. But, in order to use multi-row query, you have to use an explicit cursor. An explicit cursor contains a row-set, which is retrieved by multi-row query. Implicit cursor is used to get information about the most recent DML operation. Cursor FOR loop is used to open, fetch rows until end of cursor, and close the cursor. Input arguments of the cursor can be used to pass values to cursor at the time of opening cursor so that these values are used by SELECT command of the cursor. FOR UPDATE clause is used to override default locking and CURRENT OF is used to refer to current record in the cursor. Exercises 1. Which attribute is used to find out how many rows were fetched from cursor so far. 2. Can we use ISOPEN attribute with implicit cursor. 3. How can we know whether the most recent DML operation has affected any row? 4. How do you declare an input arguments for the cursor and how do you pass value to it? 5. What is the use of CURRENT OF clause in DELETE and UPDATE commands? 6. Create table called COURSE_DETAILS with the columns: Course Code, No. of batches completed, Total amount collected so far srikanthtechnologies.com