Download presentation
Presentation is loading. Please wait.
Published byGwen Hawkins Modified over 9 years ago
1
Chapter Seventeen Subprogramming Objective: –Procedures –Functions –Packages
2
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);
3
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);
4
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];
5
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
6
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; /
7
Chapter 17: Subprogramming7 Procedures -- To call a procedure Raise_Salary(111, 250); -- To call a procedure without parameters Proc_one; Proc_one();
8
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’);
9
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
10
Chapter 17: Subprogramming10 Constrain on Datatypes CREATE PROCEDURE AddName (Name VARCHAR2(20), …) --illegal DECLARE SUBTYPE vchar20 is VARCHAR2(20); CREATE PROCEDURE AddName (Name vchar20, …)
11
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’);
12
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];
13
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;
14
Chapter 17: Subprogramming14 Calling Functions IF Salary_OK(20000,’MANAGER’) THEN ………. -- A := Function1(); A := Function1 ;
15
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);
16
Chapter 17: Subprogramming16 Parameter Modes IN(Default)pass by reference (Read Only) OUTpass by value (Write Only) IN OUTpass by value (Read & Write)
17
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;
18
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
19
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.
20
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
21
Chapter 17: Subprogramming21 Concept of NOCOPY CREATE PROCEDURE Two (S IN OUT NOCOPY NUMBER, Value OUT NOCOPY num_varray) BEGIN ….. END;
22
Chapter 17: Subprogramming22 Dropping Functions & Procedures DROP PROCEDURE P_name; DROP FUNCTION F_name;
23
Chapter 17: Subprogramming23 Subprogram Using a Default Value CREATE PROCEDURE Three ( Today DATE DEFAULT SYSDATE, ZipCode CHAR DEFAULT ‘21532’ ) IS BEGIN …. END;
24
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(’01-12-2002’, ‘MM-DD- YYYY)); WhoIs(‘Marry’); WhoIs; WhoIs(Born_at => To_DATE(’03-03-1954’, ‘MM-DD- YYYY));
25
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;
26
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;
27
Chapter 17: Subprogramming27 Forward Declaration DECLARE PROCEDURE TWO; --Forward Declaration PROCEDURE ONE IS BEGIN TWO; END; PROCDURE TWO IS BEGIN ONE; END;
28
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.
29
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
30
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];
31
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;
32
Chapter 17: Subprogramming32 Creating Package Body: Syntax: CREATE [OR REPLACE] PACKAGE BODY p_name [IS |AS] --package boady END p_name;
33
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; /
34
Chapter 17: Subprogramming34 Use of Packages BEGIN Salary_Pack.Hire(1111,‘Lorry’) END; /
35
Chapter 17: Subprogramming35 When To Use Packages Encapsulation Data (hidden) Avoid hard-coding literals Grouping together logically related functions
36
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;
37
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?
38
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;
39
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;
40
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;
41
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; /
42
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;
43
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;
44
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
45
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;_
46
Chapter 17: Subprogramming46 Invoker’s Right: USER_USERS: USERNAME USER_ID Default_tablespace STATUS
47
Chapter 17: Subprogramming47 Subprogram Location Subprograms: Text Compiled: P_code
48
Chapter 17: Subprogramming48 Subprogram Location Example CREATE OR REPLACE PROCEDURE Simple AS a NUMBER; BEGIN a:= 10; END Simple;
49
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
50
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;
51
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;
52
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’;
53
Chapter 17: Subprogramming53 Explicit Recompilation of Procedures, Functions, Packages ALTER PROCEDURE name COMPILE; ALTER FUNCTION name COMPILE; ALTER PACKAGE name COMPILE;
54
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;
55
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.