Chapter Seventeen Subprogramming Objective: –Procedures –Functions –Packages.

Slides:



Advertisements
Similar presentations
9 Creating and Managing Tables. Objectives After completing this lesson, you should be able to do the following: Describe the main database objects Create.
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.
Procedure and Functions. Procedures Syntax: [CREATE [OR REPLACE]] PROCEDURE Pname [(p1, p2…)][IS | AS] [declarations] BEGIN [Execution Statements] [EXCEPTIONS.
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.
Advanced Package Concepts. 2 home back first prev next last What Will I Learn? Write packages that use the overloading feature Write packages that use.
1 Copyright © 2004, Oracle. All rights reserved. Creating Stored Procedures.
Creating Packages. 2 home back first prev next last What Will I Learn? Describe the reasons for using a package Describe the two components of a package:
2 Copyright © 2004, Oracle. All rights reserved. Creating Stored Functions.
Oracle PL/SQL Injection David Litchfield. What is PL/SQL? Procedural Language / Structured Query Language Oracle’s extension to standard SQL Programmable.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
Introduction to PL/SQL. Procedural Language extension for SQL Oracle Proprietary 3GL Capabilities Integration of SQL Portable within Oracle data bases.
Advanced Databases Advanced PL/SQL Programming: Procedure, Function and Package.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
ORACLE SQL. Overview Personal DBMS Vs Client/Server DBMS Oracle 8 Environment SQL – syntax and examples PL/SQL-introduction.
Copyright © SUPINFO. All rights reserved Procedures and functions.
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.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 7 PL/SQL Packages.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 6 Functions.
PL/SQLPL/SQL Oracle11g : PL/SQL Programming Chapter 6 Functions.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
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 A BRIEF OVERVIEW DAVID WILSON. PL/SQL User’s Guide and Reference PL/SQL User’s Guide and Reference.
Using Procedures & Functions Oracle Database PL/SQL 10g Programming Chapter 9.
Lecture 8 Creating Stored Functions. Objectives  After completing this lesson, you should be able to do the following:  What is Function?  Types of.
PRACTICE OVERVIEW PL/SQL Part Examine this package specification and body: Which statement about the V_TOTAL_BUDGET variable is true? A. It must.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
Distributed Database Applications COSC 5050 Week Five.
Database Application Development using PL/SQL Programming.
1 PL\SQL Dev Templates. 2 TEMPLATE DEFINITION Whenever you create a new program unit, its initial contents are based upon a template which contains pre-defined.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
Creating Functions. V 12 NE - Oracle 2006 Overview of Stored Functions A function is a named PL/SQL block that returns a value A function can be stored.
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.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
Creating Procedures. PL/SQL Program Construct Tools Constructs Anonymous Block Application procedures or functions Application packages Application Triggers.
Chapter 19: Triggers1 Chapter Nineteen Triggers Objective: – Understanding Triggers – Types of Triggers – Applications of Triggers – How to work with Triggers.
Oracle9i Developer: PL/SQL Programming Chapter 5 Functions.
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.
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.
What Are Subprograms? Subprograms are named PL/SQL blocks that can take parameters and be invoked. Subprograms allow decomposition of a program into logical.
STORED PROCEDURE & STORED FUNCTION Politeknik Telkom 2012.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
Oracle9i Developer: PL/SQL Programming Chapter 6 PL/SQL Packages.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
6 Copyright © 2009, Oracle. All rights reserved. Using Dynamic SQL.
Creating Stored Functions
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
Interacting with the Oracle Server
UNIT - V STORED PROCEDURE.
DATABASE SQL= Structure Query Language مبادئ قواعد بيانات
PL/SQL Package Week 8.
PL/SQL Scripting in Oracle:
PRACTICE OVERVIEW PL/SQL Part - 2.
Database Management Systems 2
Procedures Organized by Farrokh Alemi, Ph.D. Narrated by Yara Alemi
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
PRACTICE OVERVIEW PL/SQL Part - 1.
Prof. Arfaoui. COM390 Chapter 6
Prof. Arfaoui. COM390 Chapter 7
Presentation transcript:

Chapter Seventeen Subprogramming Objective: –Procedures –Functions –Packages

Chapter 17: Subprogramming2 Stored Procedures: Advantages of Stored Procedures: Call Stored Procedure from PL/SQL: Raise_salary ( id, amount); Call Stored Procedure from SQL: EXECUTE Raise_salary ( id, amount); Running Stored Procedure owned by other user: EXECUTE Mohsen.Raise_salary ( id, amount);

Chapter 17: Subprogramming3 Stored Procedures: Rename Stored Procedure owned by other user: CREATE SYNONYM my_Raise_salary FOR Mohsen.Raise_salary; EXECUTE my_Raise_salary ( id, amount);

Chapter 17: Subprogramming4 1 – Procedure Syntax --Header: CREATE [OR REPLACE] PROCEDURE P_Name [(P 1, P 2,..)] [ IS | AS] --Local_declarations --Body: BEGIN --Executable_statements [EXCEPTION exception_handling] END [P_Name];

Chapter 17: Subprogramming5 Procedures (Example) PROCEDURE Raise_salary (faculty_ID NUMBER, amount NUMBER) IS current_salary NUMBER;-- Declaration salary_missing EXCEPTION; BEGIN SELECT Salary INTO current_salary--Execution FROM Faculty WHERE ID=faculty_ID; IF current_salary IS NULL THEN RAISE salary_missing ELSE UPDATE Faculty SET Salary = Salary + amount WHERE ID= faculty_ID; END IF; Continued

Chapter 17: Subprogramming6 Procedures (Example) EXCEPTION--Exception WHEN NO_DATA_FOUND THEN INSERT INTO Logfile_Salary VALUES (Faculty_ID, ‘NOT exist’); WHEN salary_missing THEN INSERT INTO Logfile_Salary VALUES (Faculty_ID, ‘No Salary’); END Raise_salary; /

Chapter 17: Subprogramming7 Procedures -- To call a procedure Raise_Salary(111, 250); -- To call a procedure without parameters Proc_one; Proc_one();

Chapter 17: Subprogramming8 Actual and Formal Parameters: CREATE PROCEDURE p1 (x: STRING) BEGIN ….. END; --Procedure call n NUMBER(5); p1(n); … SQL> EXEC p1(‘Mary’);

Chapter 17: Subprogramming9 Why Use Subprogramming a.Extensibility: PROCEDURE NewDept (NewName VARCHAR2, NoFaculty NUMBER) IS BEGIN INSERT INTO Dept VALUES (NewName, NoFaculty); END; b.Abstraction c.Modularity d.Reusability e.Maintainability

Chapter 17: Subprogramming10 Constrain on Datatypes CREATE PROCEDURE AddName (Name VARCHAR2(20), …) --illegal DECLARE SUBTYPE vchar20 is VARCHAR2(20); CREATE PROCEDURE AddName (Name vchar20, …)

Chapter 17: Subprogramming11 Procedures (Example 2) CREATE OR REPLACE PROCEDURE NewStudent ( P_first Student.First%TYPE, P_last Student.Last%TYPE, P_Major Student.Major%TYPE) AS BEGIN INSERT INTO Student ( ID, First, Last, Major) VALUES (Student_sequence.NEXTVAL, P_first, P_last, P_Major); END NewStudent; ……. NewStudent(‘Jim’, ‘Johnson’, ‘COSC’);

Chapter 17: Subprogramming12 2 – Functions Syntax [CREATE [OR REPLACE]] FUNCTION F_Name [(P 1, P 2,..)] RETURN datatype [ IS | AS] Local_declaration BEGIN executable_statements [EXCEPTION exception_handling] END [F_Name];

Chapter 17: Subprogramming13 Functions (Example) CREATE FUNCTION Salary_OK ( Salary REAL, Title VARCHAR2 ) RETURN BOOLEAN -- Header IS Min_Salary REAL;-- Declaration Max_Salary REAL; BEGIN-- Execution SELECT L_Sal, H_Sal INTO Min_Salary, Max_Salary FROM Faculty WHERE Job=Title; RETURN (Salary >= Min_Salary) AND (Salary <= Max_Salary); END Salary_OK;

Chapter 17: Subprogramming14 Calling Functions IF Salary_OK(20000,’MANAGER’) THEN ………. -- A := Function1(); A := Function1 ;

Chapter 17: Subprogramming15 Calling Functions DECLARE MyName VARCHAR2(50) := F1(); Name VARCHAR2(75) := F2(‘John’); BEGIN   DECLARE a StudentInfo := StudentInfo(111, ‘Mary’, COSC’, 2.4); BEGIN …   DECLARE FacultyInfoFaculty%ROWTYPE; BEGIN FacultyInfo := F3(1111);

Chapter 17: Subprogramming16 Parameter Modes IN(Default)pass by reference (Read Only) OUTpass by value (Write Only) IN OUTpass by value (Read & Write)

Chapter 17: Subprogramming17 Example CREATE PROCEDURE One( a IN INTEGER, c IN OUT INTEGER, b OUTINTEGER) IS DECLARE x: INTEGER; y: INTEGER ; Begin b := a;-- legal a:= 10;-- illegal b:= 10;-- legal x:= c;-- legal y:=b;--possibly legal c:= 10;-- legal END;

Chapter 17: Subprogramming18 Comparison of IN, OUT, IN OUT INOUTIN OUT  Default Pass values to  Formal parameters act like a constant  Formal parameter can’t be assigned a value  Actual parameter can be constant, initialized variable, literal, or expression  Actual parameter is passed by reference  Must be specified Returns value  Formal parameters act like variable  Formal parameter must be assigned a value  Actual parameter must be a variable  Actual parameter is passed by value; Unless NOCOPY  Must be specified Pass initial value to, returns value  Formal parameters act like an initial variable  Formal parameter must be assigned a value  Actual parameter must be a variable  Actual parameter is passed by value; Unless NOCOPY

Chapter 17: Subprogramming19 Practice: Create a function to calculate the semester GPA of each student. Call it: Cal_gpa -Input student id, semester number. -Return the GPA for that student.

Chapter 17: Subprogramming20 Positional & Named Subprogram Parameters PROCEDURE Test (first REAL, second INTEGER) IS BEGIN….. END --Call procedure Test One REAL; Two INTEGER; Test (One, Two);--Positional notation Test (second => Two, first => One); --Named notation Test (first => One, second => Two); --Named notation Test (One, second => Two); --Mixed notation

Chapter 17: Subprogramming21 Concept of NOCOPY CREATE PROCEDURE Two (S IN OUT NOCOPY NUMBER, Value OUT NOCOPY num_varray) BEGIN ….. END;

Chapter 17: Subprogramming22 Dropping Functions & Procedures DROP PROCEDURE P_name; DROP FUNCTION F_name;

Chapter 17: Subprogramming23 Subprogram Using a Default Value CREATE PROCEDURE Three ( Today DATE DEFAULT SYSDATE, ZipCode CHAR DEFAULT ‘21532’ ) IS BEGIN …. END;

Chapter 17: Subprogramming24 Default Values PROCEDURE WhoIs (Name IN VARCHAR2 DEFAULT ‘Hana’, Born_at IN DATE DEFAULT SYSDATE) IS Begin….. END; --Procedure call WhoIs (‘Mary’, To_DATE(’ ’, ‘MM-DD- YYYY)); WhoIs(‘Marry’); WhoIs; WhoIs(Born_at => To_DATE(’ ’, ‘MM-DD- YYYY));

Chapter 17: Subprogramming25 Subprogram within subprogram PROCEDURE OUTSIDE (date_in IN DATE) IS PROCEDURE inside1 IS BEGIN ……. END; Function inside2 (Next_In IN INTEGER) RETURN BOOLEAN IS BEGIN ….. END; BEGIN-- OUTSIDE …. END OUTSIDE;

Chapter 17: Subprogramming26 Recursion --n!= n*(n-1)! FUNCTION fact (n POSITIVE) RETURN INTEGER IS BEGIN IF n=1 THEN RETURN 1; ELSE RETURN n* fact (n-1); END IF; END FACT;

Chapter 17: Subprogramming27 Forward Declaration DECLARE PROCEDURE TWO; --Forward Declaration PROCEDURE ONE IS BEGIN TWO; END; PROCDURE TWO IS BEGIN ONE; END;

Chapter 17: Subprogramming28 Side Effects of Subprogramming Called From SQL When a function is called from SELECT, INSERT, UPDATE, or DELETE the function can not modify any database tables. When called from INSERT, UPDATE, or DELETE the function can not query or modify any database tables modified by that statement.

Chapter 17: Subprogramming29 Side Effects of Subprogramming Called From SQL When called from SELECT, INSERT, UPDATE, or DELETE the function can not execute any: Control statement Session control System control statement DDL statement

Chapter 17: Subprogramming30 Creating Package Specification: CREATE [OR REPLACE ] PACKAGE P_name [IS |AS ] --package specification: --functions, procedures, variables, --constant, cursors, exceptions END [P_name];

Chapter 17: Subprogramming31 Packaging subprograms Package Specification: CREATE PACKAGE Salary_Pack AS SUBTYPE NameType is VARCHAR2(100); PROCEDURE Hire(Fac_Id INTEGER, Name VARCHAR2); PROCEDURE Fire(Fac_ID INTEGER); PROCEDURE Raise_Salary(Fac_Id INTEGER, Amount REAL); END Salary_Pack;

Chapter 17: Subprogramming32 Creating Package Body: Syntax: CREATE [OR REPLACE] PACKAGE BODY p_name [IS |AS] --package boady END p_name;

Chapter 17: Subprogramming33 Packaging subprograms Package Body: CREATE PACKAGE BODY Salary_Pack AS PROCEDURE Hire(Fac_Id INTEGER, Name VARCHAR2) IS BEGIN INSERT INTO faculty VALUES (fac_ID, Name); END; PROCEDURE Fire (Fac_ID INTEGER) IS BEGIN DELETE FROM Faculty WHERE ID = Fac_ID; END; PROCEDURE Raise_Salary (Fac_Id INTEGER, Amount REAL) IS Begin UPDATE faculty SET Salary = Salary + Amount WHERE ID = Fac_ID; End; END Salary_Pack; /

Chapter 17: Subprogramming34 Use of Packages BEGIN Salary_Pack.Hire(1111,‘Lorry’) END; /

Chapter 17: Subprogramming35 When To Use Packages Encapsulation Data (hidden) Avoid hard-coding literals Grouping together logically related functions

Chapter 17: Subprogramming36 Why Packages CREATE or REPLACE PROCEDURE fac_name(Fac_ID IN faculty.id%TYPE) IS FullName VARCHAR2(100); BEGIN SELECT Last_name || ‘, ‘ || first_name INTO FullName FROM faculty WHERE faculty.id = Fac_ID; END;

Chapter 17: Subprogramming37 Why Packages Problems: 1.Length of FullName is hard-coded 2.How about if I want to see ‘first, last’ name? 3.If I need different form of the same code in my applications: How should I maintain my code?

Chapter 17: Subprogramming38 Why Packages CREATE OR REPLACE PACKAGE faculty_pkg AS SUBTYPE FullName_t IS VARCHAR2(200); FUNCTION fac_Name (Last_In faculty.last_name%TYPE, First_In faculty.first_name%TYPE) RETURN fullName_t; FUNCTION fac_Name(f_id IN faculty.id%TYPE) RETURN fullName_t; END faculty_pkg;

Chapter 17: Subprogramming39 Why Packages CREATE OR REPLACE PACKAGE BODY faculty_pkg AS FUNCTION fac_Name (Last_In faculty.last_name%TYPE, First_In faculty.first_name%TYPE) RETURN fullName_t IS BEGIN RETURN Last_In || ‘, ‘ || First_In END;

Chapter 17: Subprogramming40 Why Packages FUNCTION fac_Name(f_id IN faculty.id%TYPE) RETURN fullName_t; IS temp FullName_t; BEGIN SELECT INTO temp fac_name(LastName, FirstName) FROM faculty WHERE faculty.id = id; RETURN temp; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; WHEN TOO_MANY_ROWS THEN ….. END; END faculty_pkg;

Chapter 17: Subprogramming41 Package and Local Variables: CREATE OR REPLACE PACKAGE BODY faculty_pkg IS TodayDate Date; FUNCTION fac_Name ……….. …… END fac_Name; …….. BEGIN –package SELECT SYSDATE into TodayDate FROM DUAL; END faculty_pkg; /

Chapter 17: Subprogramming42 Overloading CREATE OR REPLACE PACKAGE Student_Pack AS PROCEDURE AddStudent( P_ID IN Student.id%TYPE, P_Name IN Student.Name%TYPE, P_Major IN Student.Major%TYPE); PROCEDURE AddStudent( P_ID IN Student.id%TYPE, P_Name IN Student.Name%TYPE); END Student_Pack;

Chapter 17: Subprogramming43 Overloading CREATE OR REPLACE PACKAGE BODY Student_Pack AS PROCEDURE AddStudent( P_ID IN Student.id%TYPE, P_Name IN Student.Name%TYPE, P_Major IN Student.Major%TYPE) IS BEGIN INSERT INTO Student(id, Name, Major) VALUES (P_ID, P_Name, P_Major); END; PROCEDURE AddStudent( P_ID IN Student.id%TYPE, P_Name IN Student.Name%TYPE) IS BEGIN INSERT INTO Student(id, Name) VALUES (P_ID, P_Name); END; END Student_Pack;

Chapter 17: Subprogramming44 Restriction on Overloading Local or Packaged subprogram, or Type methods can be overloaded No overloading of two subprograms with only formal parameter different in name parameter mode or datatype No overloading of functions that differ only in return type

Chapter 17: Subprogramming45 Invoker’s Right: Stored procedure executed with the privilege of their owner; (not current user). CREATE PROCEDURE addempl( ssn NUMBER, nameVARCHAR2, salary NUMBER) AUTHID CURRENT_USER AS --vs. DEFINER BEGIN INSERT INTO employee VALUES (ssn, name, salary); END;_

Chapter 17: Subprogramming46 Invoker’s Right: USER_USERS: USERNAME USER_ID Default_tablespace STATUS

Chapter 17: Subprogramming47 Subprogram Location Subprograms: Text Compiled: P_code

Chapter 17: Subprogramming48 Subprogram Location Example CREATE OR REPLACE PROCEDURE Simple AS a NUMBER; BEGIN a:= 10; END Simple;

Chapter 17: Subprogramming49 Subprogram Location USER_OBJECTS USER_SOURCE USER_ERRORS SQL> SELECTOBJECT_NAME, OBJECT_TYPE, STATUS FROMUSER_OBJECTS WHERE OBJECT_NAME = ‘SIMPLE’; OBJECT_NAMEOBJECT_TYPESTATUS SIMPLEPROCEDUREVALID

Chapter 17: Subprogramming50 Subprogram Location SQL> SELECT TEXT FROM USER_SOURCE WHERE NAME = ‘SIMPLE’ AND TYPE= ‘PROCEDURE’ ORDER BY line; TEXT CREATE OR REPLACE PROCEDURE Simple AS a NUMBER; BEGIN a:= 10; END Simple;

Chapter 17: Subprogramming51 TABLE FUNCTION CREATE TYPE Book_Type AS OBJECT (nameVARCHAR2(50), authorVARCHAR2(30), DescriptionVARCHAR2(500)); CREATE TYPE BookSet_Type AS TABLE of Book_Type; CREATE TABLE catalogs (Name VARCHAR2(20), cat CLOB); CREATE FUNCTION GetBooks(a CLOB) RETURN BookSet_Type; SELECT X.name, y.name, y.other, y.description FROM Catalogs X, TABLE (GetBooks(x.cat)) y;

Chapter 17: Subprogramming52 Find Errors: SQL> SHOW ERRORS; -Line number of the error -Column number of the error -Text message of the error SQL> SELECT line, position, text FROM USER_ERRORS WHERE name=‘RAISE_SALARY’ AND TYPE=‘PROCEDURE’;

Chapter 17: Subprogramming53 Explicit Recompilation of Procedures, Functions, Packages ALTER PROCEDURE name COMPILE; ALTER FUNCTION name COMPILE; ALTER PACKAGE name COMPILE;

Chapter 17: Subprogramming54 Why PL/SQL? CREATE PROCEDURE proc_data (p_input IN VARCHAR2) AS BEGIN FOR i IN ( SELECT * FROMfaculty WHERE name LIKE p_input) LOOP process (i); END LOOP; END;

Chapter 17: Subprogramming55 Why PL/SQL? PL/SQL datatypes are SQL datatypes. There is tight coupling between the language and the database. No need for OPEN, CLOSE etc. Protected from many changes in the database. Portable and reusable.