Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter Sixteen Cursors Objective: – Introduction to cursors – Use of cursors in a database record – Implicit & explicit cursors – Cursors & loops – Cursors.

Similar presentations


Presentation on theme: "Chapter Sixteen Cursors Objective: – Introduction to cursors – Use of cursors in a database record – Implicit & explicit cursors – Cursors & loops – Cursors."— Presentation transcript:

1 Chapter Sixteen Cursors Objective: – Introduction to cursors – Use of cursors in a database record – Implicit & explicit cursors – Cursors & loops – Cursors with parameters

2 COSC 641 Chapter 16: PL/SQL Cursors 2 Cursors DEF: A cursor is a pointer to the context area. Context area: Memory location containing info needed to complete the PL/SQL processing

3 COSC 641 Chapter 16: PL/SQL Cursors 3 Cursors (Example 1) DECLARE V_IDStudent.id%TYPE; V_NameStudent.name%TYPE; V_MajorStudent.major%TYPE=‘COSC’; CURSOR C_Student IS SELECT id, name FROM Student WHERE major=V_Major; BEGIN OPEN C_Student; LOOP FETCH C_Student INTO V_ID, V_Name; EXIT WHEN C_Student%NOTFOUND; END LOOP; CLOSE C_Student; END;

4 COSC 641 Chapter 16: PL/SQL Cursors 4 Cursors (Example 2) CURSOR My_cursor IS SELECT a.Name, b.Name, c.Name FROM faculty a, student b, staff c WHERE a.ID = b.ID AND b.ID = c.ID;

5 COSC 641 Chapter 16: PL/SQL Cursors 5 Cursors Every SQL statement executed by the Oracle Server has an individual cursor associated with it. –Explicit cursors –Implicit cursors

6 COSC 641 Chapter 16: PL/SQL Cursors 6 Explicit Cursors (from example 1) Keep track of the current row that is processing Process row by row Programmer can manually control the cursor All in an active set Active Set 1111Mark Cursor  1231CathyCurrent row 1421Jack 1789Sandy

7 COSC 641 Chapter 16: PL/SQL Cursors 7 Controlling Explicit Cursors: 1.Create a named SQL area; (DECLARE) 2.Identify the active set (OPEN) 3.Load the current row into variables (FETCH) 4.Test for existing rows a.If found goto step 3 b.If not found goto step 5 5.Release the active set (CLOSE)

8 COSC 641 Chapter 16: PL/SQL Cursors 8 Explicit Cursor OPEN FETCH How Many Rows CLOSE

9 COSC 641 Chapter 16: PL/SQL Cursors 9 Cursors (Example 1) DECLARE V_IDStudent.id%TYPE; V_NameStudent.name%TYPE; V_MajorStudent.major%TYPE=‘COSC’; CURSOR C_Student IS SELECT id, name FROM Student WHERE major=V_Major; BEGIN OPEN C_Student; LOOP FETCH C_Student INTO V_ID, V_Name; EXIT WHEN C_Student%NOTFOUND; END LOOP; CLOSE C_Student; END;

10 COSC 641 Chapter 16: PL/SQL Cursors 10 Example CREATE OR REPLACE FUNCTION myFac(Name_In IN student.Name%TYPE) RETURN NUMBER AS CURSOR a IS SELECT Major FROM student WHERE Name = UPPER(Name_In); a_reca%ROWTYPE; Ret_valNUMBER; BEGIN OPEN a; FETCH a INTO a_rec; If a%FOUND THEN IF a_rec.Major = ‘COSC’ THEN Ret_val = 10; ELSIF a_Rec.major = ‘MATH’ THEN Ret_val = 5; END IF; CLOSE a; RETURN Ret_Val; END; /

11 COSC 641 Chapter 16: PL/SQL Cursors 11 Declaring a Cursor Syntax: CURSOR C_Name [([Parameter [, parameter])] IS Select_Statement [RETURN ret] [For UPDATE [of [COLUMN List]];

12 COSC 641 Chapter 16: PL/SQL Cursors 12 Example CURSOR C_Faculty IS SELECT * FROM Faculty WHERE Major=UPPER(‘COSC’);  -----------------------------  CURSOR C_Dept IS SELECT ID, No FROM Dept WHERE Name=UPPER(‘COSC’);  ----------------------------- 

13 COSC 641 Chapter 16: PL/SQL Cursors 13 Opening the Cursor Syntax: OPEN C_Name; OPEN is an executable statement that: 1.Dynamically allocates memory for a context area 2.Parses the SELECT statement 3.Binds the input variables: (by obtaining their memory address) 4.Identifies the active set 5.Positions the pointer just before the 1 st row in the active set

14 COSC 641 Chapter 16: PL/SQL Cursors 14 Example DECLARE CURSOR C_Faculty IS SELECT * FROM Faculty WHERE Major=‘COSC’; CURSOR C_Dept IS SELECT ID, No FROM Dept WHERE Name=‘COSC’; V_F_Name Faculty.Name%TYPE; V_F_Salary Faculty.Salary%TYPE; V_D_Rec Dept%ROWTYPE; BEGIN OPEN C_Faculty; OPEN C_Dept; ….

15 COSC 641 Chapter 16: PL/SQL Cursors 15 Fetching the Data Syntax: FETCH C_Name INTO [record_name| V1, V2, …]; 1.Retrieve the current row values into output variables 2.Match each variable to the columns 3.Test to see if the cursor points to a row FETCH statement performs: 1.Advance the pointer to the next row in the active set 2.Reads the data from the current row into the output variables 3.Exits the loop, if the pointer points to the end of the active set

16 COSC 641 Chapter 16: PL/SQL Cursors 16 Example DECLARE CURSOR C_Faculty IS SELECT * FROM Faculty WHERE Major=UPPER(‘COSC’); CURSOR C_Dept IS SELECT ID, No FROM Dept WHERE Name=‘COSC’; V_F_NameFaculty.Name%TYPE; V_F_Salary Faculty.Salary%TYPE; V_D_Rec Dept%ROWTYPE; BEGIN OPEN C_Faculty; OPEN C_Dept; FOR I IN 1..5 LOOP FETCH C_Faculty INTO V_F_Name, V_F_Salary ……… END LOOP; LOOP FETCH C_Dept INTO V_D_Rec EXIT WHEN C_Dept%NOTFOUND END LOOP; END; /

17 COSC 641 Chapter 16: PL/SQL Cursors 17 Closing the Cursor Syntax: CLOSE C_Name; 1.Close the cursor after the process is completed 2.Reopen the cursor, if it is needed OPEN_CURSORS = 50;

18 COSC 641 Chapter 16: PL/SQL Cursors 18 Illegal Cursor DECLARE CURSOR C_Student IS SELECT id, name FROM Student WHERE major=V_Major; V_Major Student.major%TYPE=‘COSC’;

19 COSC 641 Chapter 16: PL/SQL Cursors 19 ROWNUM Return a number indicating the order in which a row was selected from a table DECLARE CURSOR C1 IS SELECTID, Name FROMFaculty WHEREsalary > 40000 AND ROWNUM <=100; --100 rows CURSOR C2 IS SELECT* FROM(SELECTID, Name FROMfaculty_temp WHEREsalary> 40000 ORDER BYsalary DESC) WHERE ROWNUM <10; --first 9 sorted rows BEGIN ……… UPDATEfaculty_temp SETID = ROWNUM; --each row gets a different number END; /

20 COSC 641 Chapter 16: PL/SQL Cursors 20 Explicit Cursor Attributes %FOUNDBoolean Type C_Dept%FOUND; %NOTFOUNDBoolean Type C_Dept%NOTFOUND; %ISOPENBoolean Type C_Dept%ISOPEN; %ROWCOUNTNumber Type C_Dept%ROWCOUNT; %BULK_ROWCOUNT C_Dept% BULK_ROWCOUNT;

21 COSC 641 Chapter 16: PL/SQL Cursors 21 %ISOPEN You can fetch rows only when it is open Use %ISOPEN to check IF NOT C_faculty%ISOPEN THEN OPEN C_faculty; END IF; LOOP FETCHC_faculty into V_ID, V_Name; …

22 COSC 641 Chapter 16: PL/SQL Cursors 22 Explicit Cursor Attributes Use %ROWCOUNT cursor attribute to retrieve an exact number of rows Use %NOTFOUND cursor attribute to determine when to exit the loop SET SERVEROUTPUT ON; BEGIN …. OPENC_faculty; LOOP FETCH C_faculty INTO V_ID, V_Name; DBMS_OUTPUT.PUT_LINE (‘faculty’ || V_Name || ’has ID = ‘ || V_ID); EXIT WHEN C_faculty %ROWCOUNT >5 OR C_faculty %NOTFOUND; END LOOP; CLOSE C_faculty; END; /

23 COSC 641 Chapter 16: PL/SQL Cursors 23 Cursor Exception INVALID_CURSOR TOO_MANY_ROWS %BULK_EXCEPTION

24 COSC 641 Chapter 16: PL/SQL Cursors 24 Example DECLARE CURSOR C_Faculty IS SELECT * FROM Faculty; V_F_Rec C_Faculty%ROWTYPE; BEGIN A OPEN C_Faculty; B FETCH C_Faculty INTO V_F_Rec; C FETCH C_Faculty INTO V_F_Rec; D CLOSE C_Faculty; E F END; NameSalary Mary40,000 Mark38,000

25 COSC 641 Chapter 16: PL/SQL Cursors 25 %FOUND & %NOTFOUND C_Faculty%FOUNDC_Faculty%NOTFOUND A:ORA_1001 B:NULL C:TRUEFALSE D:TRUEFALSE E:FALSETRUE F:ORA_1001

26 COSC 641 Chapter 16: PL/SQL Cursors 26 %ISOPEN & %ROWCOUNT C_Faculty%ISOPENC_Faculty%ROWCOUNT A:FALSEORA_1001 B:TRUE0 C:TRUE1 D:TRUE2 E:FALSEORA_1001

27 COSC 641 Chapter 16: PL/SQL Cursors 27 NO_DATA_FOUND –SELECT INTO…. %NOTFOUND SQL%NOTFOUND –Cursor

28 COSC 641 Chapter 16: PL/SQL Cursors 28 Practice: Create a PL/SQL block to find the top n salaries –Use a substitution parameter so user can input n. –Use loop to get names and salaries of the top n faculty from faculty table. –Store the names and salaries in a temporary table. –Test for n=0, and n > number of faculty –Assume no two faculty members have the same salary. –Empty the table after each test.

29 COSC 641 Chapter 16: PL/SQL Cursors 29 Practice 2: –Assume faculty members may have the same salaries. In this case list all of them; –Mary10000 –Mark5000 –Sandy5000 –John2000 –If n=2; list Mary, Mark, and Sandy –If n=3; list Mary, Mark, Sandy, and John

30 COSC 641 Chapter 16: PL/SQL Cursors 30 Cursors with Parameters Syntax: CURSOR C_Name [ (P1, P2, …) ] IS Select_Statement; Where P1,P2: P [IN] datatype [[:= | DEFAULT ] exp] 1.Pass parameter values to a cursor when the cursor is opened & the query is executed 2.Open an explicit cursor several times with a different active set each time.

31 COSC 641 Chapter 16: PL/SQL Cursors 31 Example of Cursors with Parameters DECLARE CURSOR C_Student (V_ID NUMBER, V_Major VARCHAR2) IS SELECT ID, Major FROM Student WHERE Major = V_Major AND ID = V_ID; BEGIN OPEN C_Student (1111, ‘COSC’); …. CLOSE C_Student; OPEN C_Student(2222, ‘MATH’); …. CLOSE C_Student; END; /

32 COSC 641 Chapter 16: PL/SQL Cursors 32 Cursors with Parameters DECLARE V_VAR_IDStudent.ID%TYPE; V_VAR_MajorStudent.Major%TYPE:=‘COSC’; CURSOR C_Student (V_ID NUMBER, V_Major VARCHAR2) IS SELECT …. OPEN C_Student (1111, V_VAR_Major); CLOSE C_Student; OPEN C_Student (2222, ‘VART’);

33 COSC 641 Chapter 16: PL/SQL Cursors 33 Cursors with Parameters CURSOR a (Name_IN VARCHAR2) IS SELECT Major FROMStudent WHERE Name = UPPER(Name_IN); a_Reca%ROWTYPE; ret_valNUMBER; BEGIN OPENa (‘Sandy’); FETCHa INTO a_Rec; IF a%FOUND THEN IF a_Rec.Major = ‘COSC’ THEN Ret_val = 10; ELSIF a_Rec.Major = ‘MATH’ THEN Ret_val = 5; END IF; CLOSE a; END;

34 COSC 641 Chapter 16: PL/SQL Cursors 34 Open Cursor with Parameters OPEN a (:My_pack.Name); OPEN a (‘John’); OPEN a (‘Mark’);

35 COSC 641 Chapter 16: PL/SQL Cursors 35 Cursor With Parameter: CURSOR C_staff RETURN staff%ROWTYPE IS SELECT* FROMstaff WHEREdept=UPPER(‘Cosc’);

36 COSC 641 Chapter 16: PL/SQL Cursors 36 Cursor with Default Value DECLARE CURSOR C1(low NUMBER DEFAULT 0, high NUMBER DEFAULT 99) IS SELECT …

37 COSC 641 Chapter 16: PL/SQL Cursors 37 FOR UPDATE Clause Syntax: SELECT ….. FROM ….. FOR UPDATE [OF Col_Ref] [NOWAIT] - Lock the record before update or delete

38 COSC 641 Chapter 16: PL/SQL Cursors 38 Example DECLARE CURSOR C_Student IS SELECTName, ID, GPA FROM Student WHEREDept=‘COSC’ FOR UPDATE OF id, name;

39 COSC 641 Chapter 16: PL/SQL Cursors 39 WHERE CURRENT OF clause Syntax: WHERE CURRENT OF cursor Use Cursors to update or delete the current row Include the FOR UPDATE clause in the cursor query to Lock the rows first Use WHERE CURRENT OF clause to reference the current row from an explicit cursor.

40 COSC 641 Chapter 16: PL/SQL Cursors 40 Example DECLARE CURSOR C_Student IS SELECT Major, id FROM Student WHERE Major = ‘COSC’ FOR UPDATE NOWAIT; BEGIN FOR I IN C_Student LOOP UPDATEstudent SETID=student.Id * 100 WHERE CURRENT OF C_Student; END LOOP; COMMIT; END; /

41 COSC 641 Chapter 16: PL/SQL Cursors 41 Cursor with subqueries DECLARE CURSOR C1 is SELECT id, Name FROM faculty WHERE salary > ( SELECT AVG(Salary) FROM Faculty ); CURSOR C2 is SELECT * FROM (SELECT Name,Salary FROMFaculty ORDER BYSalary DESC,Name) WHERE ROWNUM<21; Continued…

42 COSC 641 Chapter 16: PL/SQL Cursors 42 Cursor FOR loops: Syntax: FOR record_name IN cursor_name LOOP statement1; statement2; …. END LOOP;

43 COSC 641 Chapter 16: PL/SQL Cursors 43 Cursor FOR loop: BEGIN FOR I IN C1 LOOP DBMS_OUTPUT.PUT_LINE(‘Above average Salary’ || I.Name); END LOOP; FOR I IN C2 LOOP DBMS_OUTPUT.PUT_LINE(‘Twenty Top paid Faculty’ || I.NAME || I.SALARY); END LOOP; END; /

44 COSC 641 Chapter 16: PL/SQL Cursors 44 NO_DATA_FOUND VS. %NOTFOUND SELECT …. INTO ….. FROM ….. WHERE ….. NO_DATA_FOUND:Exception %NOTFOUND:Flag

45 COSC 641 Chapter 16: PL/SQL Cursors 45 Implicit Cursor INSERT DELETE UPDATE SELECT INTO

46 COSC 641 Chapter 16: PL/SQL Cursors 46 Implicit Cursor DECLARE afaculty%ROWTYPE; BEGIN SELECT * INTOa FROMfaculty WHEREID = 1111; END;

47 COSC 641 Chapter 16: PL/SQL Cursors 47 Error Handling with Implicit Cursor NO_DATA_FOUND TOO_MANY_ROWS

48 COSC 641 Chapter 16: PL/SQL Cursors 48 Implicit Cursor Attributes SQL%FOUND SQL%NOTFOUND SQL%ROWCOUNT SQL%ISOPEN--Always Return False

49 COSC 641 Chapter 16: PL/SQL Cursors 49 Implicit Cursor BEGIN UPDATE classroom SETNoOfSeats= 250 WHEREroomId=111; IFSQL%NOTFOUND THEN INSERT INTO classroom (roomId, NoOfSeats) VALUES( 111, 250); END IF;

50 COSC 641 Chapter 16: PL/SQL Cursors 50 UPDATE, DELETE, INSERT SET SERVEROUTPUT ON; BEGIN UPDATEFaculty SETSalary = Salary * 0.05 WHEREDept = ‘COSC’; DBMS_OUTPUT.PUT_LINE(‘Update’ || SQL%ROWCOUNT); END; /

51 COSC 641 Chapter 16: PL/SQL Cursors 51 Cursor Variable CURSOR CURSOR Variable

52 COSC 641 Chapter 16: PL/SQL Cursors 52 Cursor Variable TYPE ref_Type IS REF CURSOR [RETURN TYPE]; Example: DECLARE TYPE stud_type REF CURSOR RETURN student%ROWTYPE; stud_cv stud_type;-- Declar Cursor Variable TYPE fac_type REF CURSOR RETURN faculty%ROWTYPE; fac_cvfac_type;

53 COSC 641 Chapter 16: PL/SQL Cursors 53 Cursor Variable Example: DECLARE TYPE FacCur_Type IS REF CURSOR RETURN faculty%ROWTYPE; Fac FacCur_Type;-- Declar Cursor Variable --Process all rows PROCEDURE p1(fac_cv IN FacCur_Type) IS person faculty%ROWTYPE; BEGIN LOOP FETCH fac_cv INTO person; EXIT WHEN fac_cv%NOTFOUND; DBMS_OUTPUT.PUT_LINE( person.name); END LOOP; END;

54 COSC 641 Chapter 16: PL/SQL Cursors 54 Cursor Variable BEGIN OPEN Fac FOR SELECT * FROM Faculty WHERE ROWNUM<=10; p1(fac); CLOSE Fac; OPEN Fac FOR SELECT * FROM Faculty WHERE name LIKE ‘X%’; p1(Fac); CLOSE Fac; END; /

55 COSC 641 Chapter 16: PL/SQL Cursors 55 Controlling Cursor Variables Cursor variables are controlled by OPEN-FOR, FETCH, CLOSE DECLARE TYPE FacCur_type IS REF CURSOR RETURN faculty%ROWTYPE; Fac FacCur_type;-- Declar Cursor Variable FacRecfaculty%ROWTYPE; BEGIN OPEN Fac FOR SELECT * FROM Faculty WHERE salary>40000; LOOP FETCH Fac INTO FacRec; EXIT WHEN Fac%NOTFOUND; DBMS_OUTPUT.PUT_LINE( FacRec.name); END LOOP; CLOSE Fac; END; /

56 COSC 641 Chapter 16: PL/SQL Cursors 56 EXAMPLE DECLARE TYPE Company_Type IS REF CURSOR RETURN Company%ROWTYPE; company_cvCompany_Type; company_RecCompany%ROWTYPE; BEING OPEN company_cv FOR SELECT * FROM Company; FETCH company_cv INTO company_Rec; CLOSE company_cv; END;

57 COSC 641 Chapter 16: PL/SQL Cursors 57 Example: DECLARE CURSOR O_CUR IS SELECTCustomer_ID, Room_No FROMOccupancy WHERER_Date = TRUNC(SYSDATE); O_Rec O_CUR%ROWTYPE; BEGIN OPEN O_CUR LOOPFETCH O_CUR INTO O_Rec; EXIT WHEN O_CUR%NOTFOUND; F1 (O_Rec.customer_ID, O_Rec.Room_No); END LOOP; CLOSE O_CUR; END; /


Download ppt "Chapter Sixteen Cursors Objective: – Introduction to cursors – Use of cursors in a database record – Implicit & explicit cursors – Cursors & loops – Cursors."

Similar presentations


Ads by Google