PL/SQL Cursors: Database Management System and Oracle 9i
PL/SQL Cursors: Database Management System and Oracle 9i
PL/SQL Cursors: Database Management System and Oracle 9i
PL/SQL CURSORS
Oracle creates a memory area, known as context area, for processing an SQL statement, which contains all information needed for processing the statement, for example, number of rows processed etc. A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set. You can name a cursor so that it could be referred to in a program to fetch and process the rows returned by the SQL statement, one at a time. There are two types of cursors:
1. Implicit Cursors Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it. Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. For INSERT operations, the cursor holds the data that need to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected. The following table provides the description of the most used attributes: Attribute %FOUND Description Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE. The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE. Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement. Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a
Page 1
%NOTFOUND
%ISOPEN %ROWCOUNT
Declaring the cursor for initializing in the memory Opening the cursor for allocating memory Fetching the cursor for retrieving data Closing the cursor to release allocated memory
A. Declaring the Cursor Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example: CURSOR c_customers IS SELECT id, name, address FROM customers; B. Opening the Cursor Opening the cursor allocates memory for the cursor, and makes it ready for fetching the rows returned by the SQL statement into it. For example, we will open above defined cursor as follows: OPEN c_customers;
Compiled By:Prof.Rinki Moolchandani Page 3
When the above code is executed at SQL prompt, it produces the following result: 1 2 3 4 5 6 Ramesh Khilan kaushik Chaitali Hardik Komal Ahmedabad Delhi Kota Mumbai Bhopal MP
Page 4