Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)

Slides:



Advertisements
Similar presentations
8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Using Explicit Cursors.
Advertisements

PL/SQL.
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
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.
Cursors How to step through the returned set of rows.
Chapter 4B: More Advanced PL/SQL Programming
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
1 Chapter 2 Reviewing Tables and Queries. 2 Chapter Objectives Identify the steps required to develop an Access application Specify the characteristics.
1 PL/SQL programming Procedures and Cursors Lecture 1 Akhtar Ali.
PL/SQL Introduction Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
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.
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:
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
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.
PL/SQL Cursors Session - II. Attributes Attributes %TYPE %ROWTYPE % Found % NotFound % RowCount % IsOPen %TYPE %ROWTYPE % Found % NotFound % RowCount.
PL SQL Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
Advanced SQL: Cursors & Stored Procedures
Advanced SQL Instructor: Mohamed Eltabakh 1 Part II.
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.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Manipulating Data in PL/SQL. 2 home back first prev next last What Will I Learn? Construct and execute PL/SQL statements that manipulate data with DML.
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)
Commercial RDBMSs Access and Oracle. Access DBMS Architchecture  Can be used as a standalone system on a single PC: -JET Engine -Microsoft Data Engine.
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
Advanced SQL: Triggers & Assertions
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.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
Cursor FOR Loops. 2 home back first prev next last What Will I Learn? List and explain the benefits of using cursor FOR loops Create PL/SQL code to declare.
Cursors For viewing and updating. Cursors How to step through the returned set of rows.
Retrieving Data in PL/SQL. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Recognize the SQL statements that can.
implicit and an explicit cursor
Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming Chapter 4.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
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.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
1 Introduction to Database Systems, CS420 SQL Persistent Stored Modules (PSM) – Stored Procedure.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
7 Copyright © 2004, Oracle. All rights reserved. Using Explicit Cursors.
CMSC-461 Database Management Systems
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.
Chapter 8 Advanced SQL Pearson Education © 2009.
Presentation transcript:

Cursors in Pl/SQL Database 1. Practice

Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary) Wines (name, type, country) Bars (name, street_number, street, city, tel) Likes (drinker, wine) Frequents (drinker, wine) Sells (bar, wine, price)

Cursors – what are they? To process an SQL statement, Oracle opens a work area called private SQL area. The private SQL area stores information needed to execute the SQL statement. An identifier called cursor lets you name a SQL statement, access the information in its private SQL area, and, to some extent, control its processing. For static SQL statements, there are two types of cursors: implicit and explicit. Oracle implicitly declares a cursor for all data definition and data manipulation statements, including SELECT statements (queries) that return only one row. However, for queries that return more than one row, to process beyond the first row, you must explicitly declare a cursor.

How to manage cursors? In the first step cursors should be declared, i.e., – the associated SQL query should be given – optionally parameters can be introduced – the return type of the cursor can also be optionally defined. Next, the cursor should be opened. The tuples of the associated SQL query should be fetched. Finally, the cursor should be closed.

Declaration of cursors Syntax: CURSOR name [(parameter[, parameter]... )] [RETURN row_type] IS sql_query; Syntax of a parameter: name [IN] type [{:= | DEFAULT} expression] Note: in the sql_query a parameter can be written wherever a constant value can be used. Virtually, the parameter is a reference, nevertheless its value cannot be changed.

Examples for declaration I. CURSOR cur_drinkers(p_year INTEGER DEFAULT 1970) IS SELECT name, salary FROM Drinkers WHERE TO_CHAR(birthday, 'YYYY') = p_year; CURSOR cur_red_wines RETURN Wines%ROWTYPE IS SELECT * FROM Wines WHERE type = 'red';

Examples for declaration II. CURSOR cur_wines(p_price NUMBER) RETURN cur_red_wines%ROWTYPE IS SELECT w.* FROM Wines w JOIN Sells ON name = wine WHERE price <= p_price;

Opening cursors When a cursor is opened, the corresponding SQL query is executed and the cursor is set to point to the first row of the result. This result is often referred as active set. Syntax: OPEN cursor_name [(parameter[, parameter]... )]; It goes without saying that the types of the parameters used in the open statement should match the types of the parameters of the cursor.

Fetching rows Syntax: FETCH cursor_name INTO variable[, variable,...]; The statement read the values of the current row and moves the cursor to the next tuple of the active set. If the cursor points to the last tuple, then the values of the variables of the INTO clause do not change. To check whether the cursor has reached the last tuple cursor attributes %FOUND and %NOTFOUND can be used.

Closing cursors Syntax: CLOSE cursor_name; The statements dissolves the relationship between the cursor and the active set.

SET SERVEROUTPUT ON DECLARE v_rowDrinkers%ROWTYPE; CURSOR c1 IS SELECT * FROM Drinkers ORDER BY birthday; BEGIN OPEN c1; LOOP FETCH c1 INTO v_row; IF c1%ROWCOUNT IN (3, 5) THEN DBMS_OUTPUT.PUT_LINE(v_row.name); END IF; EXIT WHEN c1%NOTFOUND; END LOOP; CLOSE c1; END;

Cursor attributes %FOUND: until the cursor is not opened its value is NULL. If a new row was succesfully fetched its value is set to TRUE, otherwise to FALSE. %NOTFOUND: it is the opposite of %FOUND. %ISOPEN: its value is TRUE, if the cursor has been already opened. %ROWCOUNT: before the first fetch its value is 0. After each successful fetch this value is increased by 1.

Attributes of implicit cursors After each INSERT, DELETE, UPDATE, SELECT INTO statement the system builds up an implicit cursor. Implicit cursors have similar attributes to explicit ones – %FOUND: if the statement to which the implicit cursor refers has affected at least one row, its value is TRUE, otherwise FALSE – %NOTFOUND: the opposite of %FOUND – %ISOPEN: since the system always closes the implicit cursor automatically, its value is invariably FALSE. – %ROWCOUNT: in the case of INSERT, DELETE, UPDATE statements it returns the number of the affected tuples. For SELECT INTO statements its value can only be 1, since for all other cases the system throws an exception.

Example SET SERVEROUTPUT ON DECLARE iNUMBER; BEGIN SELECT COUNT(*) INTO i FROM Dual; DBMS_OUTPUT.PUT_LINE('SQL%ROWCOUNT: ' || SQL%ROWCOUNT); DELETE FROM Wines WHERE type = 'red'; DBMS_OUTPUT.PUT_LINE('SQL%ROWCOUNT: ' || SQL%ROWCOUNT); END; Note: the implicit cursor always refers to the last executed DML or SELECT INTO statement.

CURSOR FOR loop CURSOR FOR loops offer an alternative syntax, which greatly leverages the use of cursors. Syntax: FOR loop_variable IN cursor_name [(parameters)] | (sql_query) LOOP statement [statement]... END LOOP; The type of the loop_variable is automatically set to the type of the cursor. Additionaly, the system automatically – opens the cursor – in each iteration fetches the next tuple – at the end of the loop closes the cursor.

Example for CURSOR FOR LOOP I. SET SERVEROUTPUT ON DECLARE CURSOR c1 IS SELECT * FROM Drinkers ORDER BY birthday; BEGIN LOOP v_row in c1 IF c1%ROWCOUNT IN (3, 5) THEN DBMS_OUTPUT.PUT_LINE(v_row.name); END IF; END LOOP; END;

Example for CURSOR FOR LOOP II. SET SERVEROUTPUT ON DECLARE iNUMBER:=0; BEGIN LOOP v_row in (SELECT * FROM Drinkers ORDER BY birthday) i := i+1; IF i IN (3, 5) THEN DBMS_OUTPUT.PUT_LINE(v_row.name); END IF; END LOOP; END;

Exercises 1.Write a PL/SQL program which displays the name of those drinkers, who like at least two white wines. 2.Display the price of the second and fourth most expensive wines in Joe’s bar. 3.Create a copy of the Sells table. In this table increase the price of the Brazilian and Argentinian wines by 2 and 1. 4.Create a Short_names(abbr, name) table. Insert tuples into this table s.t. the first field contains an abbreviation of the name of a drinker which is also given as the value of the second field. This abbreviation should be constructed from the original name by keeping only the first four letters. If the length of a name is less than 5, then the original name should be kept as an abbreviation.