0% found this document useful (0 votes)
7 views

RDBMS_Unit5

The document provides an overview of cursors in SQL, explaining their purpose as temporary work areas for executing SQL statements and managing data. It details two types of cursors: implicit and explicit, along with their attributes and how to work with them, including declaring, opening, fetching, and closing. Additionally, it covers cursor variables, parameterized cursors, and examples of using both strongly and weakly typed REF CURSOR.

Uploaded by

aavishkaarclub
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

RDBMS_Unit5

The document provides an overview of cursors in SQL, explaining their purpose as temporary work areas for executing SQL statements and managing data. It details two types of cursors: implicit and explicit, along with their attributes and how to work with them, including declaring, opening, fetching, and closing. Additionally, it covers cursor variables, parameterized cursors, and examples of using both strongly and weakly typed REF CURSOR.

Uploaded by

aavishkaarclub
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

10/7/2019

Cursors
Unit 5

Prepared By Shimi Biju 1

Cursor
 A cursor is a temporary work area created in the system memory
when a SQL statement is executed.
 A cursor contains information on a select statement and the rows
of data accessed by it.
 This temporary work area is used to store the data retrieved from
the database, and manipulate this data.
 A cursor can hold more than one row, but can process only one
row at a time.
 The set of rows the cursor holds is called the active set.

Prepared By Shimi Biju 2

1
10/7/2019

Types of Cursors
 There are two types of cursors −
 Implicit cursors
 Explicit cursors

Prepared By Shimi Biju 3

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 needs to be
inserted.
 For UPDATE and DELETE operations, the cursor identifies the
rows that would be affected.

Prepared By Shimi Biju 4

2
10/7/2019

Implicit cursor Attributes


 In PL/SQL, you can refer to the most recent implicit cursor as
the SQL cursor, which always has attributes such as %FOUND,
%ISOPEN, %NOTFOUND, and %ROWCOUNT.
S.No Attribute & Description
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
1
or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
2
statement affected no rows, or a SELECT INTO statement returned no rows.
Otherwise, it returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.
Prepared By Shimi Biju 5

 Any SQL cursor attribute will be accessed as sql%attribute_name


as shown below in the example.
 Example
 Select * from customers;

| ID | NAME | AGE | ADDRESS | SALARY |


| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
Prepared By Shimi Biju 6

3
10/7/2019

The following program will update the table and increase the salary of
each customer by 500 and use the SQL%ROWCOUNT attribute to
determine the number of rows affected −

DECLARE
total_rows number(2);
BEGIN
UPDATE customers SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
Prepared By Shimi Biju 7

 If you check the records in customers table, you will find that the rows
have been updated −
 Select * from customers;

| ID | NAME | AGE | ADDRESS | SALARY |


| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |

Prepared By Shimi Biju 8

4
10/7/2019

Explicit Cursors

 Explicit cursors are programmer-defined cursors for gaining more


control over the context area.
 An explicit cursor should be defined in the declaration section of
the PL/SQL Block.
 It is created on a SELECT Statement which returns more than one
row.

 The syntax for creating an explicit cursor is −

 CURSOR cursor_name IS select_statement;

Prepared By Shimi Biju 9

Working with an explicit cursor


 Working with an explicit cursor includes the following steps −

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Prepared By Shimi Biju 10

5
10/7/2019

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;

Prepared By Shimi Biju 11

Opening the Cursor

 Opening the cursor allocates the memory for the cursor and
makes it ready for fetching the rows returned by the SQL
statement into it.
 For example, we will open the above defined cursor as follows −

 OPEN c_customers;

Prepared By Shimi Biju 12

6
10/7/2019

Fetching the Cursor

 Fetching the cursor involves accessing one row at a time. For


example, we will fetch rows from the above-opened cursor as
follows −

 FETCH c_customers INTO c_id, c_name, c_addr;

Prepared By Shimi Biju 13

Closing the Cursor

 Closing the cursor means releasing the allocated memory. For


example, we will close the above-opened cursor as follows −

 CLOSE c_customers;

Prepared By Shimi Biju 14

7
10/7/2019

 When a cursor is opened, the first row becomes the current row.
 When the data is fetched it is copied to the record or variables and
the logical pointer moves to the next row and it becomes the
current row.
 On every fetch statement, the pointer moves to the next row.
 If you want to fetch after the last row, the program will throw an
error.
 When there is more than one row in a cursor we can use loops
along with explicit cursor attributes to fetch all the records.

Prepared By Shimi Biju 15

Points to remember while fetching a row:

 We can fetch the rows in a cursor to a PL/SQL Record or a list of


variables created in the PL/SQL Block.
 If you are fetching a cursor to a PL/SQL Record, the record
should have the same structure as the cursor.
 If you are fetching a cursor to a list of variables, the variables
should be listed in the same order in the fetch statement as the
columns are present in the cursor.

Prepared By Shimi Biju 16

8
10/7/2019

General Form of using an explicit cursor

 DECLARE
variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;

Prepared By Shimi Biju 17

Explicit Cursor Attributes

Prepared By Shimi Biju 18

9
10/7/2019

Table records.
DECLARE
emp_rec emp_tbl%rowtype;
CURSOR emp_cur IS
SELECT * FROM customers
WHERE salary > 10;
BEGIN
OPEN emp_cur;
FETCH emp_cur INTO emp_rec;
dbms_output.put_line (emp_rec.first_name || ' ' || emp_rec.last_name);
CLOSE emp_cur;
END;

Prepared By Shimi Biju 19

Cursor-based records.
 The following example illustrates the concept of cursor-based records.
 DECLARE
 CURSOR customer_cur is
 SELECT id, name, address
 FROM customers;
 customer_rec customer_cur%rowtype;
 BEGIN
 OPEN customer_cur;
 LOOP
 FETCH customer_cur into customer_rec;
 EXIT WHEN customer_cur%notfound;
 DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name);
 END LOOP;
 END;

Prepared By Shimi Biju 20

10
10/7/2019

Cursor with Variables


DECLARE
c_id customers.id%type;
c_name customer.Name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
Prepared By Shimi Biju 21

Cursor For Loops


 General Syntax for using FOR LOOP:

 FOR record_name IN cusror_name


 LOOP
 process the row...
 END LOOP;

Prepared By Shimi Biju 22

11
10/7/2019

DECLARE
CURSOR emp_cur IS
SELECT first_name, last_name, salary FROM emp_tbl;
emp_rec emp_cur%rowtype;
BEGIN
FOR emp_rec in sales_cur
LOOP
dbms_output.put_line(emp_cur.first_name || ' ' |emp_cur.last_name
|| ' ' ||emp_cur.salary);
END LOOP;
END;
Prepared By Shimi Biju 23

Cursor Variables
 A cursor variable is a variable that references to a cursor.
 Different from implicit and explicit cursors, a cursor variable is
not tied to any specific query. Meaning that a cursor variable can
be opened for any query.
 The most important benefit of a cursor variable is that it enables
passing the result of a query between PL/SQL programs.
 Without a cursor variable, you have to fetch all data from a
cursor, store it in a variable e.g., a collection, and pass this
variable as an argument.
 With a cursor variable, you simply pass the reference to that
cursor.

Prepared By Shimi Biju 24

12
10/7/2019

Defining Cursor Variables

 Cursor variables are defined using a REF CURSOR type. The type is
defined in one of two ways:

 Strongly Typed - The REF CURSOR type is restricted to an individual


return type using the RETURN clause. Although this reduces the
chances of runtime errors since column mismatches are detected at
compilation time, it also limits the overall flexibility of the type.

 Weakly Typed - The RETURN clause is omitted allowing the type to


reference any return type. This gives greater flexibility, but it increases
the likelihood of runtime errors because column mismatches are not
picked up at compile time.

Prepared By Shimi Biju 25

example of a strong REF CURSOR


DECLARE
TYPE customer_t IS REF CURSOR RETURN
customers%ROWTYPE;
c_customer customer_t;

This form of cursor variable called strong typed REF CURSOR


because the cursor variable is always associated with a specific
record structure, or type.

Prepared By Shimi Biju 26

13
10/7/2019

example of a weak REF CURSOR


 Example of a weak typed REF CURSOR declaration that is not
associated with any specific structure:

DECLARE
TYPE customer_t IS REF CURSOR;
c_customer customer_t;

Prepared By Shimi Biju 27

Strongly typed REF CURSOR.


DECLARE
TYPE t_ref_cursor IS REF CURSOR RETURN
cursor_variable_test%ROWTYPE;
c_cursor t_ref_cursor;
l_row cursor_variable_test%ROWTYPE;
BEGIN
DBMS_OUTPUT.put_line('Strongly typed REF CURSOR');
OPEN c_cursor FOR SELECT * FROM cursor_variable_test;
LOOP
FETCH c_cursor INTO l_row;
EXIT WHEN c_cursor%NOTFOUND;
DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description);
END LOOP;
CLOSE c_cursor;
END;
Prepared By Shimi Biju 28

14
10/7/2019

Weakly typed REF CURSOR.


DECLARE
TYPE t_ref_cursor IS REF CURSOR;
c_cursor t_ref_cursor;
l_row cursor_variable_test%ROWTYPE;
BEGIN
DBMS_OUTPUT.put_line('Weakly typed REF CURSOR');
OPEN c_cursor FOR SELECT * FROM cursor_variable_test;
LOOP
FETCH c_cursor INTO l_row;
EXIT WHEN c_cursor%NOTFOUND;
DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description);
END LOOP;
CLOSE c_cursor;
END;

Prepared By Shimi Biju 29

SYS_REFCURSOR
 The SYS_REFCURSOR cursor variable is an Oracle-defined
weak Ref-Cursor type, which is pre-declared in the STANDARD
package.
 We are free to use this Ref-Cursor type as parameters for our sub-
routines and return type for the functions without needing to
create them in a package specification, as it is already done by
Oracle for us.
 As SYS_REFCURSOR is a weakly typed Ref-Cursor, it assumes
any record structure as its return type during its run time.
 When we open a cursor variable created with the
SYS_REFCURSOR type, a reference is created in the SGA,
which can be then passed to another program or client
environment as a cursor variable.
Prepared By Shimi Biju 30

15
10/7/2019

Weakly typed REF CURSOR using SYS_RECURSOR.


- Weakly typed REF CURSOR using SYS_RECURSOR.

DECLARE
c_cursor SYS_REFCURSOR;
l_row cursor_variable_test%ROWTYPE;
BEGIN
DBMS_OUTPUT.put_line('Weakly typed REF CURSOR using SYS_RECURSOR');

OPEN c_cursor FOR


SELECT * FROM cursor_variable_test;

LOOP
FETCH c_cursor INTO l_row;
EXIT WHEN c_cursor%NOTFOUND;
DBMS_OUTPUT.put_line(l_row.id || ' : ' || l_row.description);
END LOOP;
CLOSE c_cursor;
END;
Prepared By Shimi Biju 31

Parameterized Cursors
 The parameterized cursors are the further extension to the explicit
cursors having IN type parameters for limiting the number of
rows processed by the cursor associated SELECT statement while
opening them.

Prepared By Shimi Biju 32

16
10/7/2019

PL/SQL Weak Parameterized Cursors

 These types of cursors do not have any return type and are
generally used in procedures, functions and anonymous blocks
which are not encapsulated within a package.

Prepared By Shimi Biju 33

 A cursor is created over the EMPLOYEES table with an input


parameter, which is placed in the SELECT statement’s WHERE
condition.
 When the cursor is opened with an employee ID as its parameter
value, it acts as a row limiter and returns only the row set
corresponding to that particular employee ID, which is then
fetched and processed, instead of processing all the employees

Prepared By Shimi Biju 34

17
10/7/2019

DECLARE
l_rt_emp employees%rowtype;
CURSOR cur(ip_n_emp_id NUMBER) IS
SELECT * FROM employees WHERE
employee_id=ip_n_emp_id;
BEGIN
OPEN cur(:ip_n_emp_id);
FETCH cur INTO l_rt_emp;
dbms_output.put_line(l_rt_emp.last_name||', '||l_rt_emp.first_name);
CLOSE cur;
END;

Prepared By Shimi Biju 35

PL/SQL Strong Parameterized Cursors

 These cursors have a return type and are primarily used in


procedures, functions and anonymous blocks which are
encapsulated within a package.
 The return type serves no other purpose than letting its calling
environment know its structure from its package specification
while hiding its business complexities and rules in its body.

Prepared By Shimi Biju 36

18
10/7/2019

 Oracle PL/SQL Cursors With Parameters


 Cursors With Parameters

 We can pass parameters into a cursor and use them in the query.

 We can only pass values to the cursor; and cannot pass values out of the
cursor through parameters.

 Only the datatype of the parameter is defined, not its length.

 Optionally, we can also give a default value for the parameter, which
will take effect if no value is passed to the cursor.

Prepared By Shimi Biju 37

Cursors With Parameters Example


The following cursor prints department number and name in one
line followed by employees working in that department (name and
salary) and total salary.
DECLARE
CURSOR cur_dept IS SELECT * FROM dept ORDER BY deptno;
CURSOR cur_emp (par_dept VARCHAR2) IS
SELECT ename, salary FROM emp
WHERE deptno = par_dept ORDER BY ename;
r_dept DEPT%ROWTYPE;
var_ename EMP.ENAME%TYPE;
var_salary EMP.SALARY%TYPE;
var_tot_salary NUMBER (10,2);

Prepared By Shimi Biju 38

19
10/7/2019

 BEGIN
 OPEN cur_dept;
 LOOP
 FETCH cur_dept INTO r_dept;
 EXIT WHEN cur_dept%NOTFOUND;
 DBMS_OUTPUT.PUT_LINE ('Department : ' || r_dept.deptno || ' - '|| r_dept.dname);
 var_tot_salary := 0;
 OPEN cur_emp (r_dept.deptno);
 LOOP
 FETCH cur_emp INTO var_ename, var_salary;
 EXIT WHEN cur_emp%NOTFOUND;
 DBMS_OUTPUT.PUT_LINE ('Name: ' ||var_ename || ' Salary:'||var_salary);
 var_tot_salary := var_tot_salary + var_salary;
 END LOOP;
 CLOSE cur_emp;
 DBMS_OUTPUT.PUT_LINE ('Total Salary for Dept: ' || var_tot_salary);
 END LOOP;
 CLOSE cur_dept;
 END;
Prepared By Shimi Biju 39

20

You might also like