Les 05
Les 05
G.Srinivas
[email protected]
1
Objectives
2
About Cursors
3
Explicit Cursor Functions
Table
100 King AD_PRES
101 Kochhar AD_VP
Active set
102 De Haan AD_VP
Cursor
. . .
. . .
. . .
139 Seo ST_CLERK
140 Patel ST_CLERK
. . .
4
Controlling Explicit Cursors
No
Yes
DECLARE OPEN FETCH EMPTY? CLOSE
5
Controlling Explicit Cursors
6
Controlling Explicit Cursors
Cursor
pointer
7
Controlling Explicit Cursors
Cursor
pointer
8
Declaring the Cursor
Syntax:
CURSOR cursor_name IS
•
select_statement;
Do not include the INTO clause in the cursor declaration.
• If processing rows in a specific sequence is required, use the ORDER BY clause in the query.
9
Declaring the Cursor
Example:
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name
FROM employees;
CURSOR dept_cursor IS
SELECT *
FROM departments
WHERE location_id = 170;
BEGIN
...
10
Opening the Cursor
Syntax:
OPEN cursor_name;
11
Fetching Data from the Cursor
Syntax:
FETCH cursor_name INTO [variable1, variable2, ...]
| record_name];
12
Fetching Data from the Cursor
Example:
LOOP
FETCH emp_cursor INTO v_empno,v_ename;
EXIT WHEN ...;
...
-- Process the retrieved data
…
END LOOP;
13
Closing the Cursor
Syntax:
CLOSE cursor_name;
14
Explicit Cursor Attributes
15
The %ISOPEN Attribute
16
Controlling Multiple Fetches
17
The %NOTFOUND
and %ROWCOUNT Attributes
18
Example
DECLARE
v_empno employees.employee_id%TYPE;
v_ename employees.last_name%TYPE;
CURSOR emp_cursor IS
SELECT employee_id, last_name
FROM employees;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_empno, v_ename;
EXIT WHEN emp_cursor%ROWCOUNT > 10 OR
emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE (TO_CHAR(v_empno)
||' '|| v_ename);
END LOOP;
CLOSE emp_cursor;
END ;
19
Cursors and Records
Process the rows of the active set by fetching values
into a PL/SQL RECORD.
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name
FROM employees;
emp_record emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_record;
...
emp_record
employee_id last_name
100 King
20
Cursor FOR Loops
Syntax:
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
DECLARE
CURSOR emp_cursor IS
SELECT last_name, department_id
FROM employees;
BEGIN
FOR emp_record IN emp_cursor LOOP
-- implicit open and implicit fetch occur
IF emp_record.department_id = 80 THEN
...
END LOOP; -- implicit close occurs
END;
/
22
Cursor FOR Loops Using Subqueries
23
Summary