100% found this document useful (1 vote)
65 views11 pages

Understanding Cursors in Oracle SQL

1) Cursors allow programmers to retrieve and process data from database tables one row at a time. There are two types of cursors: implicit cursors which are used for queries returning a single row, and explicit cursors which are used for queries returning multiple rows. 2) Explicit cursors must be declared, opened, have records fetched from them one by one, and then closed. They provide more programmatic control over processing query results. 3) Cursor attributes like %FOUND, %NOTFOUND and %ROWCOUNT can be used to check the status of a cursor and the number of rows it has processed.

Uploaded by

Selvaraj V
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
65 views11 pages

Understanding Cursors in Oracle SQL

1) Cursors allow programmers to retrieve and process data from database tables one row at a time. There are two types of cursors: implicit cursors which are used for queries returning a single row, and explicit cursors which are used for queries returning multiple rows. 2) Explicit cursors must be declared, opened, have records fetched from them one by one, and then closed. They provide more programmatic control over processing query results. 3) Cursor attributes like %FOUND, %NOTFOUND and %ROWCOUNT can be used to check the status of a cursor and the number of rows it has processed.

Uploaded by

Selvaraj V
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Oracle Concepts

Selvaraj V
Anna University Chennai.
Chennai – 25.
Cursors:

A cursor is a pointer to a memory location where the results of a "select statement"


could be stored and we could manipulate the information by fetching the records.

Two types of classification - I and II

Implicit and Explicit

Implicit : More fast and less coding effort. Will never raise INVALID_CURSOR
error Cannot be opened outside the statement Raises NO_DATA_FOUND and
TOO_MANY_ROWS exceptions (eg: select <stmt>)

Implicit cursor returning more than one record? FOR LOOP cursors.

Explicit : 2 network round trips. Store data first then retrieve data. More
programmatic control.

Programmer could open; fetch data, close, check attributes etc.

Static and Dynamic

Static : Normal cursor (implicit or explicit)

Dynamic : Ref cursor: Cursor created only when it is opened.


Could be declared once and defined many times in different procedures.
Ref Cursors can have Record/s as return types. So could be used for returning
data to other languages like Java, C++ etc

II.b) Ref cursor - Two types

Strong : Ref cursor with a specified return type.


Weak : No return type specified.

3. Cursor attributes

%FOUND - records fetched successfully


%NOTFOUND - no records fetched
%ROWCOUNT - Number of records fetched
%ISOPEN - returns TRUE if cursor is open

Could be used for implicit and explicit cursors.


Eg:
Implicit:
select * from emp -- also for delete
operations
If SQL%FOUND then
v_count:= SQL%ROWCOUNT
end if;

Explicit:
open c1; -- cursor c1 is select
<stmt>
fetch <>
exit when c1%NOTFOUND

Eg: Explicit cursor.

Declare

Cursor cur1 is
select ename,empno,sal from emp
where empno between 9000 and 1000
and sal<50000
and deptno=50

begin

open cur1;

fetch cur1 into v_ename,v_empno,v_sal;


exit when cur1%notfound;

---<do processing>

close cur1;

end;
CURSOR

For every SQL statement execution certain area in memory is allocated. PL/SQL
allow you to name this area. This private SQL area is called context area or cursor. A
cursor acts as a handle or pointer into the context area. A PL/SQL program controls
the context area using the cursor. Cursor represents a structure in memory and is
different from cursor variable.
When you declare a cursor, you get a pointer variable, which does not point any
thing. When the cursor is opened, memory is allocated and the cursor structure is
created. The cursor variable now points the cursor. When the cursor is closed the
memory allocated for the cursor is released.
Cursors allow the programmer to retrieve data from a table and perform actions on
that data one row at a time. There are two types of cursors implicit cursors and
explicit cursors.

Implicit cursors

For SQL queries returning single row PL/SQL declares implicit cursors. Implicit
cursors are simple SELECT statements and are written in the BEGIN block
(executable section) of the PL/SQL. Implicit cursors are easy to code, and they
retrieve exactly one row. PL/SQL implicitly declares cursors for all DML statements.
The most commonly raised exceptions here are NO_DATA_FOUND or
TOO_MANY_ROWS.
Syntax:

SELECT ename, sal INTO ena, esa FROM EMP WHERE EMPNO = 7844;

Note: Ename and sal are columns of the table EMP and ena and esa are the variables

used to store ename and sal fetched by the query.


Explicit Cursors

Explicit cursors are used in queries that return multiple rows. The set of rows fetched
by a query is called active set. The size of the active set meets the search criteria in
the select statement. Explicit cursor is declared in the DECLARE section of PL/SQL
program.

Syntax:

CURSOR <cursor-name> IS <select statement>

Sample Code:

DECLARE
CURSOR emp_cur IS SELECT ename FROM EMP;
BEGIN
----
---
END;
Processing multiple rows is similar to file processing. For processing a file you need
to open it, process records and then close. Similarly user-defined explicit cursor
needs to be opened, before reading the rows, after which it is closed. Like how file
pointer marks current position in file processing, cursor marks the current position in
the active set.

Opening Cursor

Syntax: OPEN <cursor-name>;

Example : OPEN emp_cur;

When a cursor is opened the active set is determined, the rows satisfying the where
clause in the select statement are added to the active set. A pointer is established
and points to the first row in the active set.
Fetching from the cursor: To get the next row from the cursor we need to use fetch
statement.

Syntax: FETCH <cursor-name> INTO <variables>;

Example: FETCH emp_cur INTO ena;

FETCH statement retrieves one row at a time. Bulk collect clause need to be used to
fetch more than one row at a time.
Closing the cursor: After retrieving all the rows from active set the cursor should be
closed. Resources allocated for the cursor are now freed. Once the cursor is closed
the execution of fetch statement will lead to errors.

CLOSE <cursor-name>;

Explicit Cursor Attributes

Every cursor defined by the user has 4 attributes. When appended to the cursor
name these attributes let the user access useful information about the execution of a
multirow query.

The attributes are:

1. %NOTFOUND: It is a Boolean attribute, which evaluates to true, if the


last fetch failed. i.e. when there are no rows left in the cursor to fetch.
2. %FOUND: Boolean variable, which evaluates to true if the last fetch,
succeeded.
3. %ROWCOUNT: It’s a numeric attribute, which returns number of rows
fetched by the cursor so far.
4. %ISOPEN: A Boolean variable, which evaluates to true if the cursor is
opened otherwise to false.
In above example I wrote a separate fetch for each row, instead loop statement
could be used here. Following example explains the usage of LOOP.
Using WHILE:

While LOOP can be used as shown in the following example for accessing the cursor
values.

Example:

Fetch is used twice in the above example to make %FOUND available. See below
example.
Using Cursor For Loop:

The cursor for Loop can be used to process multiple records. There are two benefits
with cursor for Loop

1. It implicitly declares a %ROWTYPE variable, also uses it as LOOP index


2. Cursor For Loop itself opens a cursor, read records then closes the cursor
automatically. Hence OPEN, FETCH and CLOSE statements are not necessary in it.
Example:

emp_rec is automatically created variable of %ROWTYPE. We have not used OPEN,


FETCH , and CLOSE in the above example as for cursor loop does it automatically.
The above example can be rewritten as shown in the Fig , with less lines of code. It
is called Implicit for Loop.
Deletion or Updation Using Cursor:

In all the previous examples I explained about how to retrieve data using cursors.
Now we will see how to modify or delete rows in a table using cursors. In order to
Update or Delete rows, the cursor must be defined with the FOR UPDATE clause. The
Update or Delete statement must be declared with WHERE CURRENT OF

Following example updates comm of all employees with salary less than 2000 by
adding 100 to existing comm.

Common questions

Powered by AI

The %NOTFOUND cursor attribute is crucial in loop constructs to determine when a loop processing a set of database query results should be terminated. This Boolean attribute evaluates to true if the last fetch from a cursor failed, indicating that there are no more rows left to fetch from the active set . Within loops, %NOTFOUND is often used as a condition to exit, ensuring that the loop stops processing once all records have been processed, thus preventing errors from trying to fetch non-existent data . This attribute maintains the robustness and correctness of query processing logic within loops.

Implicit cursors are automatically created by PL/SQL for single-row queries, such as simple SELECT statements, and for DML statements. They are faster and require less coding effort, but they automatically raise errors like NO_DATA_FOUND or TOO_MANY_ROWS when something goes wrong . In contrast, explicit cursors are used for multi-row queries, offering more programmatic control by allowing the developer to explicitly open, fetch, and close the cursor. This means explicit cursors do not automatically handle errors, requiring the programmer to manage exception handling manually .

A developer might choose implicit cursors for simplicity and performance in cases where single-row queries or simple DML operations are needed. Implicit cursors are automatically managed by PL/SQL, reducing coding effort and execution time since they do not require explicit open, fetch, and close operations . They are particularly beneficial for straightforward database transactions where the overhead and complexity of explicit cursor management are unnecessary. Implicit cursors handle many aspects automatically, including error management through exceptions like NO_DATA_FOUND, making them practical for less complex scenarios .

Cursor attributes such as %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN are appended to explicit cursors to provide essential information about query execution. %FOUND evaluates to true if the last fetch succeeded, while %NOTFOUND is true if it failed, thus helping control loops that process query results . %ROWCOUNT provides the count of rows fetched so far, useful for tracking progress in multi-row operations. %ISOPEN indicates whether the cursor is open, assisting in preventing errors from operations on closed cursors . These attributes enable precise control over data retrieval and error handling during multi-row query processing.

Update or delete operations using cursors involve defining the cursor with a FOR UPDATE clause and using the WHERE CURRENT OF syntax to modify specific rows . This approach is more programmatically controlled, allowing developers to dynamically select, loop through, and alter each row meeting certain criteria, which is beneficial when complex row-based logic is required. Conventional SQL update or delete statements modify sets of records in a single operation without the need for iterative processing, which is more efficient for bulk operations lacking conditional logic. However, using cursors provides higher granularity and control over operations involving each row .

The cursor FOR loop simplifies cursor management by automatically handling the opening, fetching, and closing of cursors. It declares an implicit %ROWTYPE variable and uses it as the loop index . This minimizes coding effort and reduces potential for errors by removing the need for separate OPEN, FETCH, and CLOSE statements within the loop, thereby streamlining code development and maintenance . Additionally, the cursor FOR loop facilitates cleaner code structures by encapsulating loop controls and cursor operations in fewer lines of code .

Ref cursors in PL/SQL, particularly weak ref cursors, do not have a predefined return type, making them highly flexible for returning various result sets to other programming languages . They enable PL/SQL blocks to pass datasets to Java or C++ applications by acting as query result sets that can be iterated over within these languages . This capability allows developers to implement complex data operations in PL/SQL while leveraging Java or C++ for user interface or further processing, facilitating seamless integration of database operations with application development.

Strong ref cursors have a specified return type, which enforces stricter type checking and provides clear guarantees about the structure of the returned dataset . This helps in ensuring consistency and safety in PL/SQL programs, especially in situations requiring predictable data structures. Weak ref cursors, on the other hand, do not have a predefined type, offering greater flexibility as they can be associated with queries returning varying columns or datasets. This flexibility makes them suitable for dynamic query scenarios, but they require additional handling to manage potential runtime type issues, impacting program design by necessitating checks for data consistency .

Dynamic cursors, often realized as REF cursors, are preferable when you need to execute queries in which the SQL statement is not entirely known until runtime, or when you need to return query results to external programs such as Java or C++ applications . They allow flexibility by not being bound to a single SQL statement upon declaration, unlike static cursors. A REF cursor can be defined and assigned at runtime, providing adaptive query execution capabilities, which is a significant advantage when creating modular and reusable code in application development .

In PL/SQL, the context area is a memory region allocated when a SQL statement is executed; it stores metadata about the statement execution and the results of the query . A cursor acts as a handle or pointer to the context area, allowing programs to control and manage the information within it. When a cursor is declared and opened, the context area is initialized, and when closed, the resources are released. Efficient memory management through the context area is essential for optimizing performance and ensuring resources are freed after query execution, preventing memory leaks in PL/SQL applications .

You might also like