Working with Explicit Cursors
An explicit cursor is a SELECT statement that is explicitly defined in the declaration section of your code and, in the process, assigned a name. There is no such thing as an explicit cursor for UPDATE, DELETE, and INSERT statements.
With explicit cursors, you have complete control over the different PL/SQL steps involved in retrieving information from the database. You decide when to OPEN the cursor, when to FETCH records from the cursor (and therefore from the table or tables in the SELECT statement of the cursor), how many records to fetch, and when to CLOSE the cursor. Information about the current state of your cursor is available through examination of cursor attributes. This granularity of control makes the explicit cursor an invaluable tool for your development effort.
Let’s look at an example. The following function determines (and returns) the level of jealousy I should feel for my friends, based on their location.
1 CREATE OR REPLACE FUNCTION jealousy_level ( 2 NAME_IN IN friends.NAME%TYPE) RETURN NUMBER 3 AS 4 CURSOR jealousy_cur 5 IS 6 SELECT location FROM friends 7 WHERE NAME = UPPER (NAME_IN); 8 9 jealousy_rec jealousy_cur%ROWTYPE; 10 retval NUMBER; 11 BEGIN 12 OPEN jealousy_cur; 13 14 FETCH jealousy_cur INTO jealousy_rec; 15 16 IF jealousy_cur%FOUND 17 THEN 18 IF jealousy_rec.location = 'PUERTO RICO' 19 THEN retval := 10; 20 ELSIF jealousy_rec.location = 'CHICAGO' 21 THEN retval := 1; 22 END IF; 23 END IF; 24 25 CLOSE jealousy_cur; ...
Get Oracle PL/SQL Programming, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.