Chapter Eighteen Cursors

Slides:



Advertisements
Similar presentations
Definition Cursor is a control structure for the successive traversal of records in a result set. Cursor is a record pointer in a database. DATABASE CURSOR.
Advertisements

8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Using Explicit Cursors.
PL/SQL.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Chapter 4B: More Advanced PL/SQL Programming
PL/SQL Agenda: Basic PL/SQL block structure
Oracle PL/SQL Eyad Husni Elshami. Why PL/SQL Block Structures: – PL/SQL consists of blocks of code, which can be nested within each other. Each block.
Programming in Oracle with PL/SQL
Oracle 8 Training PL/SQL. What is PL/SQL? PL/SQL stands for "Procedural Language extensions to SQL”. PL/SQL look very similar to the SQL language but.
1 PL/SQL programming Procedures and Cursors Lecture 1 Akhtar Ali.
1 Agenda Summary of last class Loops Simple Loops WHILE Loops FOR Loops Records Cursors.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
PL/SQL Bulk Collections in Oracle 9i and 10g Kent Crotty Burleson Consulting October 13, 2006.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
Distributed Database Applications COSC 5050 Week Three.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
SAGE Computing Services Customised Oracle Training Workshops and Consulting Are you making the most of PL/SQL? Hints and tricks and things you may have.
Program with PL/SQL. Interacting with the Oracle Server.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Cursors These slides are licensed under.
Cursor. Cursors Operations Cursors adalah suatu nama area yang berisi hasil dari suatu statement SQL. 1. OPEN 2. FETCH 3. CLOSE.
PL/SQL Cursors Session - II. Attributes Attributes %TYPE %ROWTYPE % Found % NotFound % RowCount % IsOPen %TYPE %ROWTYPE % Found % NotFound % RowCount.
L/O/G/O Working with Composite Data Types. Objectives After completing this lesson, you should be able to do the following: –Create user-defined PL/SQL.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
1 CursorsCursors. 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two.
Trapping Oracle Server Exceptions. 2 home back first prev next last What Will I Learn? Describe and provide an example of an error defined by the Oracle.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Trigger Oracle PL/SQL. Triggers Associated with a particular table Associated with a particular table Automatically executed when a particular event occurs.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
Dynamic SQL Oracle Database PL/SQL 10g Programming Chapter 13.
Copyright  Oracle Corporation, All rights reserved. 18 Interacting with the Oracle Server.
Using SQL in PL/SQL ITEC 224 Database Programming.
Chapter Sixteen Cursors Objective: – Introduction to cursors – Use of cursors in a database record – Implicit & explicit cursors – Cursors & loops – Cursors.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
Oracle11g: PL/SQL Programming Chapter 3 Handling Data in PL/SQL Blocks.
implicit and an explicit cursor
Chapter 18: Exception Handling1 Chapter Eighteen Exception Handling Objective: – Define exceptions – List types of exception handlers – Trap errors – Exception.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
PL/SQL  PL/SQL stands for Procedural Language/SQL.  PL/SQL extends SQL by adding constructs found in procedural languages like procedures, loops, variables,
Database An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL Definition: PL/SQL.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
PLSQL Cont…. Most Common Oracle Data Types VARCHAR2 –Stores variable-length character data. –Takes a required parameter that specifies a maximum length.
7 Copyright © 2004, Oracle. All rights reserved. Using Explicit Cursors.
PL/SQL CURSORS.
ITEC 224 Database Programming
CS322: Database Systems PL/ SQL PL/SQL by Ivan Bayross.
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
Interacting with the Oracle8 Server
Interacting with the Oracle Server
Interacting with the Oracle Server
Interacting with the Oracle Server
PL/SQL.
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Cursors ITEC 224 Database Programming PL/SQL Lab.
Database Management Systems 2
Agenda Summary of last class Cursors Loops Records Simple Loops
Database Management Systems 2
Database Management Systems 2
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Cursors.
Chapter 8 Advanced SQL Pearson Education © 2009.
Presentation transcript:

Chapter Eighteen Cursors Chapter 18: Cursors Chapter Eighteen Cursors Objective: Introduction to cursors Use of cursors in a record variable Implicit & explicit cursors Cursors & loops Cursors with parameters COSC 641

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

Cursors (Example) DECLARE V_ID Student.id%TYPE; V_Name Student.name%TYPE; V_Major Student.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; Chapter 18: Cursors

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; Chapter 18: Cursors

Cursors Every SQL statement is executed by the Oracle Server has a cursor associated with it. Explicit cursors Implicit cursors Chapter 18: Cursors

Explicit Cursors Keep track of the current row that is processing Active Set 1111 Mark Cursor  1231 Cathy Current row 1421 Jack 1789 Sandy Keep track of the current row that is processing Process row by row Programmer can manually control the cursor All in an active set Chapter 18: Cursors

Controlling Explicit Cursors: Create a named SQL area; Declare the cursor Identify the active set Load the current row into variables Test for existing rows If found goto step 3 If not found goto step 5 Release the active set Chapter 18: Cursors

Explicit Cursor Control retrieval of information: OPEN FETCH How Many Rows Close Chapter 18: Cursors

Cursors (Example) DECLARE V_ID Student.id%TYPE; V_Name Student.name%TYPE; V_Major Student.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; Chapter 18: Cursors

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_rec a%ROWTYPE; Ret_val NUMBER; BEGIN OPEN a FETCH a INTO a_rec; If a%FOUND THEN IF a_rec.Major = ‘COSC’ THEN Ret_val = 10; ELSEIF a_Rec.major = ‘MATH’ THEN Ret_val = 5; ENDIF ENDIF; CLOSE a; RETURN Ret_Val; END; Chapter 18: Cursors

Controlling Explicit Cursors: DECLARE OPEN FETCH Test for empty rows No: goto 3 Yes: goto 5 CLOSE Chapter 18: Cursors

Declaring a Cursor Syntax: CURSOR C_Name [([Parameter [, parameter])] IS Select_Statement [RETURN ret] [For UPDATE [of [COLUMN List]]; Chapter 18: Cursors

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

Example ----------------------------- CURSOR c_student (student_ID IN NUMBER) IS SELECT Name FROM student WHERE student_ID = student.ID; ----------------------------- CURSOR staff_cur RETURN staff%ROWTYPE SELECT * FROM staff WHERE dept = UPPER(‘COSC’); Chapter 18: Cursors

Opening the Cursor Syntax OPEN C_Name; OPEN is an executable statement that performs: Dynamically allocates memory for a context area Parses the SELECT statement Binds the input variables: (obtain their memory address) Identifies the active set Positions the pointer just before the 1st row in the active set Chapter 18: Cursors

Example DECLARE CURSOR C_Faculty IS CURSOR C_Dept IS SELECT * FROM F aculty 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; Chapter 18: Cursors

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

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_Name Faculty.Name%TYPE; V_F_Salary Faculty.Salary%TYPE; V_D_Rec Dept%ROWTYPE; BEGIN OPEN C_Faculty; OPEN C_Dept; Chapter 18: Cursors

Example 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 Chapter 18: Cursors

Closing the Cursor Syntax CLOSE C_Name; Close the cursor after the process is completed Reopen the cursor, if it is needed OPEN_CURSORS = 50 Chapter 18: Cursors

Cursor Attributes %FOUND Boolean Type %NOTFOUND Boolean Type My_CUR%FOUND; %NOTFOUND Boolean Type My_CUR%NOTFOUND; %ISOPEN Boolean Type My_CUR%ISOPEN; %ROWCOUNT Number Type My_CUR%ROWCOUNT; %BULK_ROWCOUNT My_CUR% BULK_ROWCOUNT; Chapter 18: Cursors

Cursor Exception INVALID_CURSOR TO)_MANY_ROWS %BULK_EXCEPTION Chapter 18: Cursors

Example DECLARE Name Salary Mary 40,000 Mark 38,000 BEGIN END; CURSOR C_Faculty IS SELECT * FROM Faculty; V_F_Rec C_Faculty%ROWTYPE; BEGIN OPEN C_Faculty FETCH C_Faculty INTO V_F_Rec; CLOSE C_Faculty; END; Name Salary Mary 40,000 Mark 38,000 Chapter 18: Cursors

%FOUND & %NOTFOUND C_Faculty%FOUND C_Faculty%NOTFOUND A: ORA_1001 B: NULL C: TRUE FALSE D: E: F: Chapter 18: Cursors

%ISOPEN & %ROWCOUNT C_Faculty%ISOPEN C_Faculty%ROWCOUNT A: FALSE ORA_1001 B: TRUE C: 1 D: 2 E: F: Chapter 18: Cursors

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

Cursors with Parameters Example: 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’); Chapter 18: Cursors

Cursors with Parameters DECLARE V_VAR_ID Student.ID%TYPE; V_VAR_Major Student.Major%TYPE:=‘COSC’; CURSOR C_Student (V_ID NUMBER, V_Major VARCHAR2) IS SELECT …. OPEN C_Student (1111, V_VAR_Major); OPEN C_Student (2222, ‘VART’); Chapter 18: Cursors

Cursors with Parameters CURSOR a (Name_IN VARCHAR2) IS SELECT Major FROM Student WHERE Name = UPPER(Name_IN); a_rec a%ROWTYPE; ret_val NUMBER; BEGIN OPEN a (‘Major’); FETCH a INTO a_Rec; IF a%ROWTYPE THEN IF a_Rec,Major = ‘COSC’ THEN Ret_val = 10; ELSEIf a_Rec.Major = ‘MATH’ THEN Ret_val = 5; ENDIF ENDIF; CLOSE a; END; Chapter 18: Cursors

Open Cursor with Parameters OPEN a (:My_pack.Name); OPEN a (‘John’); OPEN a (‘Mark’); Chapter 18: Cursors

FOR UPDATE Syntax SELECT ….. FROM ….. FOR UPDATE [OF Col_Ref] [NOWAIT] Lock the record before update Chapter 18: Cursors

Example DECLARE CURSOR C_Student IS SELECT * FROM Student FOR UPDATE OF id, name; Chapter 18: Cursors

Example DECLARE CURSOR C_Student IS SELECT Major, id FROM Student WHERE Major = ‘COSC’ FOR UPDATE NOWAIT; Chapter 18: Cursors

NO_DATA_FOUND VS. %NOTFOUND SELECT …. INTO ….. FROM ….. WHERE ….. NO_DATA_FOUND :Exception %NOTFOUND :Flag Chapter 18: Cursors

BULK COLLECT BC can retrieve multiple rows of data Reduce Number of context switches between the PL/SQL & SQL Reduce the overhead of data retrieval Chapter 18: Cursors

BULK COLLECT DECLARE TYPE n IS TABLE OF Student.ID%TYPE; TYPE m IS TABLE OF Student.Major%TYPE; a n; b m; CURSOR Temp IS SELECT ID, Major FROM Student WHERE Dept=‘COSC’; Chapter 18: Cursors

BULK COLLECT END; BEGIN Open Temp; FETCH Temp BULK COLLECTION INTO a, b; CLOSE Temp; END; Chapter 18: Cursors

BULK COLLECT DECLARE TYPE T_Number IS TABLE OF Temp_Table.ID%TYPE; TYPE T_String IS TABLE OF Temp_Table.Major%TYPE; V_Num T_Number:=T_Number(1); V_String T_String := T_String(1); CURSOR Temp IS SELECT Major FROM Temp_Table WHERE ID > 1111 ORDER BY ID; Chapter 18: Cursors

BULK COLLECT END; BEGIN V_Number.EXTEND(1000); V_String.EXTEND(1000); -- Load data into Temp_Table SELECT ID, Major FROM Temp_Table BULK COLLECTION INTO V_Num, V_String ORDER BY ID; END; Chapter 18: Cursors

Implicit Cursor INSERT DELETE UPDATE SELECT INTO DECLARE a faculty%ROWTYPE; BEGIN SELECT * INTO a FROM faculty WHERE ID = 1111; END; Chapter 18: Cursors

Error Handling with Implicit Cursor NO_DATA_FOUND TOO_MANY_ROWS Chapter 18: Cursors

Implicit Cursor Attributes SQL%FOUND SQL%NOTFOUND SQL%ROWCOUNT SQL%ISOPEN --Always Return False Chapter 18: Cursors

Implicit Cursor BEGIN UPDATE classroom SET NoOfSeats= 250 WHERE roomId=111; IF SQL%NOTFOUND THEN INSERT INTO classroom (roomId, NoOfSeats) VALUES( 111, 250); END IF; Chapter 18: Cursors

Implicit Cursor BEGIN UPDATE classroom SET NoOfSeats= 250 WHERE roomId=111; IF SQL%ROWCOUNT= 0 THEN INSERT INTO classroom (roomId, NoOfSeats) VALUES( 111, 250); ENDIF; Chapter 18: Cursors

Cursor Variable CURSOR CURSOR Variable Chapter 18: Cursors

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_cv fac_type; TYPE List IS TABLE of student%TYPE; a List; Chapter 18: Cursors

Controlling Cursor Variables OPEN-FOR, FETCH, CLOSE Example: OPEN stud_cv FOR SELECT name, ID FROM Student; FETCH stud_cv INTO a; Chapter 18: Cursors

EXAMPLE DECLARE TYPE Company_Type IS REF CURSOR RETURN Company%ROWTYPE; company_cv Company_Type; company_Rec Company%ROWTYPE; BEING OPEN company_cv FOR SELECT * FROM Company; FETCH company_cv INTO company_Rec; CLOSE company_cv; END; Chapter 18: Cursors