1 Oracle PL/SQL III Cursors Procedures Functions iSQLplus:

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Oracle PL/SQL IV Exceptions Packages.
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.
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Chapter 9: Advanced SQL and PL/SQL Topics Guide to Oracle 10g.
1 Copyright © 2004, Oracle. All rights reserved. Creating Stored Procedures.
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.
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
1 PL/SQL programming Procedures and Cursors Lecture 1 Akhtar Ali.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
Advanced Databases Advanced PL/SQL Programming: Procedure, Function and Package.
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.
Stored Procedures Functions Packages
Copyright  Oracle Corporation, All rights reserved. 3 Creating Procedures.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Revision on Triggers and Cursors. Walk through of exam type question. Question 1. A trigger is required to automatically update the number of rooms available.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 6 Functions.
PL/SQLPL/SQL Oracle11g : PL/SQL Programming Chapter 6 Functions.
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. 1. Which type of argument passes a value from a procedure to the calling program? A. VARCHAR2 B. BOOLEAN C. OUT D. IN 2.
Advanced SQL: Cursors & Stored Procedures
Program with PL/SQL Lesson 4. Writing Control Structure.
Advanced SQL Instructor: Mohamed Eltabakh 1 Part II.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
PL/SQL Procedural Language / Structured Query Language.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
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.
implicit and an explicit cursor
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
PL/SQL. What is PL/SQL  Procedural Language – SQL  An extension to SQL with design features of programming languages (procedural and object oriented)
Passing Parameters. 2 home back first prev next last What Will I Learn? List the types of parameter modes Create a procedure that passes parameters Identify.
A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows: CREATE.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
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.
Oracle9i Developer: PL/SQL Programming Chapter 5 Functions.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Lab 2 Writing PL/SQL Blocks CISB514 Advanced Database Systems.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
Stored Procedures and Functions Pemrograman Basis Data MI2183.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
A Guide to SQL, Seventh Edition
Creating Stored Procedures and Functions
Difference between Oracle PL/SQL and MySQL
PL/SQL.
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
SQL PL/SQL Presented by: Dr. Samir Tartir
PRACTICE OVERVIEW PL/SQL Part - 2.
Sa0951a PL/SQL 1: Introduction
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Chapter 8 Advanced SQL Pearson Education © 2009.
Prof. Arfaoui. COM390 Chapter 6
Stored Procedure Language
Presentation transcript:

1 Oracle PL/SQL III Cursors Procedures Functions iSQLplus:

2 Remember the SELECT INTO…… ? It only allowed the retrieval of one row Select attribute into variable from … where … Or Select count(*) into variable from ……… But when we want to retrieve multiple rows we need to use what is called a CURSOR

3 What is the Cursor structure? Declare it – This is achieved by a SELECT command – And by giving the CURSOR a name Open it Fetch row(s) from it Close it

4 Declaring the Cursor DECLARE CURSOR low_pay IS SELECT surname,salary FROM Personnel where salary < 12000; v_surnamepersonnel.surname%TYPE; v_salarypersonnel.salary%TYPE; BEGIN ….. Because a cursor is associated with multiple rows they are normally used with LOOP structures

5 OPEN, FETCH, CLOSE, %NOTFOUND DECLARE CURSOR low_pay IS SELECT surname,salary FROM Personnel where salary < 30000; v_surnamepersonnel.surname%TYPE; v_salarypersonnel.salary%TYPE; BEGIN OPEN low_pay; LOOP FETCH low_pay INTO v_surname, v_salary; EXIT when low_pay%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_surname ||' '|| v_salary); END LOOP; CLOSE low_pay; END; Block1

6 A variation using WHILE Loop and %FOUND DECLARE CURSOR low_pay IS SELECT surname,salary FROM Personnel where salary < 30000; v_surnamepersonnel.surname%TYPE; v_salarypersonnel.salary%TYPE; BEGIN OPEN low_pay; FETCH low_pay INTO v_surname, v_salary; WHILE low_pay%FOUND LOOP DBMS_OUTPUT.PUT_LINE(v_surname ||' '|| v_salary); FETCH low_pay INTO v_surname, v_salary; END LOOP; CLOSE low_pay; END; Note 2 FETCH commands

7 Parameters in Cursors DECLARE CURSOR c_salary (p_min number,p_max number) IS SELECT surname,salary FROM Personnel where salary between p_min and p_max; v_surnamePersonnel.surname%TYPE; v_salaryPersonnel.salary%TYPE; BEGIN OPEN c_salary(&p_min, &p_max); LOOP FETCH c_salary INTO v_surname, v_salary; EXIT WHEN c_salary%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_surname||' '||v_salary); END LOOP; CLOSE c_salary; END; These would be in quotes for VARCHAR2 variables Block2

8 FOR LOOP requires no CURSOR OPEN, FETCH, CLOSE DECLARE CURSOR c_salary IS SELECT surname,salary FROM Personnel where salary < 30000; BEGIN FOR counter in c_salary LOOP DBMS_OUTPUT.PUT_LINE(counter.surname ||' '||counter.salary); END LOOP END;

9 SELECT FOR UPDATE Cursors DECLARE CURSOR c_salary IS SELECT surname,salary FROM Personnel FOR UPDATE; v_surnamepersonnel.surname%TYPE; v_salarypersonnel.salary%TYPE; BEGIN OPEN c_salary; LOOP FETCH c_salary INTO v_surname, v_salary; EXIT WHEN c_salary%NOTFOUND; UPDATE Personnel SET BONUS=v_salary*0.05 WHERE CURRENT of c_salary; END LOOP; CLOSE c_salary; END; Useful when updating or deleting each row fetched in a cursor otherwise all would be updated at once

10 Stored Procedures A unit of code that performs one or more tasks After completion, execution returns to the calling block To run the procedure at any time, use EXECUTE CREATE OR REPLACE PROCEDURE proc_name IS …….. BEGIN ….. END proc_name;

11 Example Procedure with a cursor CREATE OR REPLACE PROCEDURE surnames IS CURSOR c_staff IS SELECT surname FROM Personnel where div=10; BEGIN FOR names IN c_staff LOOP DBMS_OUTPUT.PUT_LINE(names.surname); END LOOP END; The message ‘Procedure created’ should be displayed

12 Example Procedure to update salaries and how to test it CREATE OR REPLACE PROCEDURE sal_update IS BEGIN UPDATE personnel set salary=salary*1.1 where div=10; END; Execute sal_update; Select salary from personnel where div=10; - to test the procedure Block3

13 Passing parameters CREATE OR REPLACE PROCEDURE test (firstparIN varchar2, secondparINDate) IS empnamevarchar2(30); empidnumber(8); BEGIN …….. END; Parameter nameParameter modedatatype IN is the default if no mode specified Notice parameter declarations are unconstrained

14 IN CREATE OR REPLACE PROCEDURE t (p_salaryIN Number) IS BEGIN …….. p_salary:=p_salary + 100; END; This is illegal as parameter can only be referenced, not changed CREATE OR REPLACE PROCEDURE t (p_salaryIN Number, IS v_salarynumber(15); BEGIN …….. v_salary:=p_salary + 100; END; This is legal as parameter is assigned to a variable first

15 IN Example CREATE OR REPLACE PROCEDURE proc_IN (p_branchNumberIN Number, p_percentINNumber) IS BEGIN UPDATE Personnel set salary=salary+salary*p_percent/100 where div = p_branchNumber; END; EXECUTE proc_IN(10,25) Block4

16 Actual and Formal parameters CREATE OR REPLACE PROCEDURE updperc (p_percentIN Number, p_Emp INNumber) IS CURSOR staff_cur IS SELECT joindate, div from Personnel where managedBy=p_Emp; BEGIN For stf in staff_cur LOOP updStaff(stf.joindate,stf.div); END LOOP; … END; Formal Actual CREATE OR REPLACE PROCEDURE updstaff (p_joindate IN Date, p_div IN Number) IS …. EXECUTE updperc(10,3455) The Calling Procedure

17 Another Calling Example DECLARE v_varNUMBER := 20; BEGIN delete_staff(v_var); END; CREATE OR REPLACE PROCEDURE delete_staff (p_branchNumberIN Number) IS BEGIN DELETE Personnel WHERE div=p_branchNumber; END; Anonymous block calls procedure Block5

18 Using parameters in Loops To execute this procedure (e.g insert values from 30 to 32) EXECUTE insert_root(30,32) CREATE OR REPLACE PROCEDURE insert_root (from_val NUMBER, to_val NUMBER) IS num NUMBER; BEGIN FOR num IN from_val.. to_val LOOP INSERT INTO roots VALUES (num, SQRT(num)); END LOOP; END;

19 FUNCTIONS Functions are similar to procedures They are used for calculations and returning a value CREATE OR REPLACE FUNCTION function_name(parameter list) RETURN return_datatype IS … variables, cursors etc BEGIN Execution code ………………; Return expression; END; Can be: NUMBER VARCHAR2 BOOLEAN etc

20 RETURN Statement Determines – The point at which execution returns to the calling block AND the value that is assigned to it RETURN expression – Where expression can be any legal PL/SQL expression v_salary := get_salary(10) Block calls the function get_salary for employee 10 Get_salary will return the salary for employee 10 and this will be assigned to v_salary

21 Example Function SET SERVEROUTPUT ON DECLARE V_divID personnel.div%type; v_divName branch.DivName%type:='&divName'; V_aveSalary personnel.salary%type; BEGIN SELECT div into v_divID FROM branch WHERE divname=v_divName; v_aveSalary:=get_aveSal(v_divID); DBMS_OUTPUT.PUT_LINE('Division '||v_divID||' has '||v_aveSalary||' average salary'); END; CREATE OR REPLACE FUNCTION get_aveSal (i_div IN NUMBER) RETURN number IS v_salary personnel.salary%type; BEGIN SELECT avg(salary) INTO v_salary FROM Personnel WHERE div=i_div; RETURN v_salary; END get_aveSal; "get the average salary for ADMIN" Block prompts for division name then passes the division number to the function get_aveSal Block6

22 Summary CURSORS – To process all rows of a selected set STORED PROCEDURES – Parameters – Calling them FUNCTIONS – Parameters – Return – Calling them

23 READING Connolly/Begg (4th ed) Earp/Bagui Ch. 12, 13 Shah Part 3 (Ch 10,12) Morrison/Morrison Ch.4, 9 – selected bits Casteel, J (2003). Oracle 9i Developer: PL/SQL Programming