Professional Documents
Culture Documents
CURSORS1
CURSORS1
CURSORS1
CURSORS
1
INTRODUCTION:
o A cursor is a mechanism that allows to retrieve rows one at a time
from a relation.
o It is a solution for impedance mismatch problem that occurs
because SQL operates on sets of records, whereas languages like C
do not cleanly support a set-of-records abstraction.
o We can declare a cursor on any relation or on any SQL query.
2
o Once a cursor is declared we can do the following operations:
i. Open it
ii. Fetch the next row
iii. Move the cursor :
a. To the next row
b. To the row after next ‘n’
c. To the first row
d. To the previous row
iv. Close the cursor
3
CURSOR DEFINITION & USAGE
Cursors enable us to examine in the host language program a
collection of rows computed by an embedded SQL statement:
We need to open a cursor if the embedded statement is a SELECT
(i.e., a query).
However, we can avoid opening a cursor if the answer contains a single
row, as we will see shortly.
4
EXAMPLE :
We can find the name and age of a sailor,
specified by assigning a value to the host variable c_sid, declared earlier,as
follows :
EXEC SQL SELECT S.sname, S.age
INTO :c_sname, :c_age
FROM Sailors S
WHERE S.sid = :c sid;
The INTO clause allows us to assign the columns of the single answer row
to the host variables c_sname and c_age.
Thus, we do not need a cursor to embed this query in a host language
program.
5
EXAMPLE:
The following query, computes the
names and ages of all sailors with a rating greater than the current
value of the host variable c_minrating:
OPEN sinfo;
o The value of c_minrating is the value of this variable when we open the
cursor.
NOTE: The cursor declaration is processed at compile time, and the
OPEN 7
o When a cursor is opened, it is positioned just before the first row.
o FETCH command can be used to read the first row of cursor sinfo into
host language variables:
CLOSE sinfo;
9
PROPERTIES OF CURSORS:
The general form of a cursor declaration is:
DECLARE cursorname [INSENSITIVE] [SCROLL] CURSOR FOR
some query
[ORDER BY order-item-list]
[FOR READ ONLY | FOR UPDATE]
A cursor can be declared to be a read-only cursor (FOR READ ONLY)
or, to be an updatable cursor (FOR UPDATE).
If it is updatable, then the UPDATE and DELETE commands allow us
to update or delete the row on which the cursor is positioned.
10
EXAMPLE:
UPDATE Sailors S
SET S.rating=s.rating-1
WHERE CURRENT of sinfo;
EXAMPLE:
DELETE Sailors S
WHERE CURRENT of sinfo;
EXAMPLE:
Modify rating values in Sailor rows by
concurrently executing the command:
UPDATE Sailors S
SET
S.rating=S.rating – 1; 12
o If INSENSITIVE is specified, then all answers were computed and stored
when sinfo was opened.
o Thus , the update command has no effect on the rows fetched by sinfo if
it is executed after sinfo is opened.
o If INSENSITIVE is not specified, then the behaviour is implementation
dependent.
13
THANK YOU
14