Entry Level Technology Program

Creating Packages

Satyam Learning Center

PL/SQL

1 of 1

Objectives
Entry Level Technology Program

After completing this lesson, you should be able to do the following:  Describe packages and list their possible components  Create a package to group together related variables, cursors, constants, exceptions, procedures, and functions  Designate a package construct as either public or private  Invoke a package construct  Describe a use for a bodiless package

Satyam Learning Center

PL/SQL

2 of 1

Overview of Packages
Entry Level Technology Program

Packages:  Group logically related PL/SQL types, items, and subprograms  Consist of two parts:  Specification  Body  Cannot be invoked, parameterized, or nested  Allow the Oracle server to read multiple objects into memory at once

Satyam Learning Center

PL/SQL

3 of 1

Components of a Package
Entry Level Technology Program

Package specification

Public variable Procedure A declaration Public procedure

Private variable

Package body

Procedure B definition Procedure A definition

Private procedure

Public procedure Local variable

Satyam Learning Center

PL/SQL

4 of 1

Referencing Package Objects
Entry Level Technology Program

Package specification

Procedure A declaration

Package body

Procedure B definition Procedure A definition

Satyam Learning Center

PL/SQL

5 of 1

Developing a Package Entry Level Technology Program Editor Code 1 iSQL*Plus 2 Load and run the file.sql Oracle Source code Compile P code Execute Satyam Learning Center PL/SQL 6 of 1 .

but a package body cannot exist without a package specification.  A package specification can exist without a package body.Developing a Package Entry Level Technology Program  Saving the text of the CREATE PACKAGE statement in two different SQL files facilitates later modifications to the package. Satyam Learning Center PL/SQL 7 of 1 .

 The REPLACE option drops and recreates the package specification.  Variables declared in the package specification are initialized to NULL by default.  All the constructs declared in a package specification are visible to users who are granted privileges on the package. Satyam Learning Center PL/SQL 8 of 1 .Entry Level Technology Program Creating the Package Specification Syntax: CREATE [OR REPLACE] PACKAGE package_name IS|AS public type and item declarations subprogram specifications END package_name.

Declaring Public Constructs Entry Level Technology Program COMM_PACKAGE package G_COMM Package specification 1 RESET_COMM procedure declaration 2 Satyam Learning Center PL/SQL 9 of 1 .

10. RESET_COMM is a public procedure that is implemented in the package body. PL/SQL 10 of 1 Satyam Learning Center .10. END comm_package.Entry Level Technology Program Creating a Package Specification: Example CREATE OR REPLACE PACKAGE comm_package IS g_comm NUMBER := 0.10 PROCEDURE reset_comm (p_comm IN NUMBER). / • • G_COMM is a global variable and is initialized to 0. --initialized to 0.

Creating the Package Body Entry Level Technology Program Syntax: CREATE [OR REPLACE] PACKAGE BODY package_name IS|AS private type and item declarations subprogram bodies END package_name. Identifiers defined only in the package body are private constructs. • • The REPLACE option drops and recreates the package body. • All private constructs must be declared before they are used in the public constructs. These are not visible outside the package body. PL/SQL 11 of 1 Satyam Learning Center .

Entry Level Technology Program Public and Private Constructs COMM_PACKAGE package G_COMM Package specification 1 2 RESET_COMM procedure declaration Package body VALIDATE_COMM function definition 3 RESET_COMM procedure definition 2 Satyam Learning Center PL/SQL 12 of 1 .

END validate_comm. ELSE RETURN(TRUE). IF p_comm > v_max_comm THEN RETURN(FALSE).. END IF.. Satyam Learning Center PL/SQL 13 of 1 .Entry Level Technology Program Creating a Package Body: Example comm_pack. BEGIN SELECT MAX(commission_pct) INTO v_max_comm FROM employees.sql CREATE OR REPLACE PACKAGE BODY comm_package IS FUNCTION validate_comm (p_comm IN NUMBER) RETURN BOOLEAN IS v_max_comm NUMBER. .

--reset global variable ELSE RAISE_APPLICATION_ERROR(-20210. END comm_package. END reset_comm. END IF. / Satyam Learning Center PL/SQL 14 of 1 .sql PROCEDURE reset_comm (p_comm IN NUMBER) IS BEGIN IF validate_comm(p_comm) THEN g_comm:=p_comm.'Invalid commission').Entry Level Technology Program Creating a Package Body: Example comm_pack.

.. Satyam Learning Center PL/SQL 15 of 1 . 'Invalid commission'). PROCEDURE reset_comm (p_comm IN NUMBER) IS BEGIN IF validate_comm(p_comm) THEN g_comm := p_comm. END reset_comm. END comm_package. ELSE RAISE_APPLICATION_ERROR (-20210. END IF.Entry Level Technology Program Invoking Package Constructs Example 1: Invoke a function from a procedure within the same package. CREATE OR REPLACE PACKAGE BODY comm_package IS .

p_yard OUT NUMBER) IS BEGIN p_yard := p_meter * global_consts. / VARIABLE yard NUMBER EXECUTE meter_to_yard (1.Referencing a Public Variable from a Stand-Alone Procedure Entry Level Technology Program Example: CREATE OR REPLACE PROCEDURE meter_to_yard (p_meter IN NUMBER. END meter_to_yard.meter_2_yard. :yard) PRINT yard Satyam Learning Center PL/SQL 16 of 1 .

Removing Packages Entry Level Technology Program To remove the package specification and the body. To remove the package body. use the following syntax: DROP PACKAGE BODY package_name. use the following syntax: DROP PACKAGE package_name. Satyam Learning Center PL/SQL 17 of 1 .

 The package specification should contain as few constructs as possible. Satyam Learning Center PL/SQL 18 of 1 .Guidelines for Developing Packages Entry Level Technology Program  Construct packages for general use.  The package specification should contain only those constructs that you want to be public.  Changes to the package specification require recompilation of each referencing subprogram.  Place items in the declaration part of the package body when you must maintain them throughout a session or across transactions.  Define the package specification before the body.

 Hiding information:  Only the declarations in the package specification are visible and accessible to applications. Satyam Learning Center PL/SQL 19 of 1 .  Private constructs in the package body are hidden and inaccessible.  Easier application design: Code and compile specification and body separately.  All coding is hidden in the package body.Advantages of Packages Entry Level Technology Program  Modularity: Encapsulate related constructs.

 There is only one copy in memory for all users.  The dependency hierarchy is simplified.  Overloading: Multiple subprograms of the same name Satyam Learning Center PL/SQL 20 of 1 .Advantages of Packages Entry Level Technology Program  Added functionality: Persistency of variables and cursors  Better performance:  The entire package is loaded into memory when the package is first referenced.

management.Summary Entry Level Technology Program In this lesson. you should have learned how to:  Improve organization. and performance by using packages  Group related procedures and functions together in a package  Change a package body without affecting a package specification  Grant security access to the entire package Satyam Learning Center PL/SQL 21 of 1 . security.

Summary Entry Level Technology Program In this lesson. you should have learned how to:  Hide the source code from users  Load the entire package into memory on the first call  Reduce disk access for subsequent calls  Provide identifiers for the user session Satyam Learning Center PL/SQL 22 of 1 .

Summary Entry Level Technology Program Command Task Create (or modify) an existing CREATE [OR REPLACE] PACKAGE package specification Create (or modify) an existing CREATE [OR REPLACE] PACKAGE package body BODY DROP PACKAGE Remove both the package specification and the package body DROP PACKAGE BODY Remove the package body only Satyam Learning Center PL/SQL 23 of 1 .

or a package  Requires the formal parameters of the subprograms to differ in number. or data type family  Enables you to build more flexibility because a user or application is not restricted by the specific data type or number of formal parameters Note: Only local or packaged subprograms can be overloaded.Overloading Entry Level Technology Program  Enables you to use the same name for different subprograms inside a PL/SQL block. 24 of 1 Satyam Learning Center PL/SQL . You cannot overload stand-alone subprograms. order. a subprogram.

p_loc IN departments. p_loc IN departments.sql CREATE OR REPLACE PACKAGE over_pack IS PROCEDURE add_dept (p_deptno IN departments.department_name%TYPE DEFAULT 'unknown'.Overloading: Example Entry Level Technology Program over_pack.department_name%TYPE DEFAULT 'unknown'.department_id%TYPE. END over_pack. / Satyam Learning Center PL/SQL 25 of 1 . p_name IN departments. PROCEDURE add_dept (p_name IN departments.location_id%TYPE DEFAULT 0).location_id%TYPE DEFAULT 0).

p_name IN departments. p_name.department_name%TYPE DEFAULT 'unknown'.location_id%TYPE DEFAULT 0) IS BEGIN INSERT INTO departments (department_id. p_loc).NEXTVAL. department_name. department_name. p_loc IN departments. PROCEDURE add_dept (p_name IN departments.sql CREATE OR REPLACE PACKAGE BODY over_pack IS PROCEDURE add_dept (p_deptno IN departments.location_id%TYPE DEFAULT 0) IS BEGIN INSERT INTO departments (department_id. p_loc). END add_dept. p_loc IN departments. END over_pack.department_name%TYPE DEFAULT 'unknown'. location_id) VALUES (departments_seq.Overloading: Example Entry Level Technology Program over_pack_body.department_id%TYPE. / Satyam Learning Center PL/SQL 26 of 1 . location_id) VALUES (p_deptno. p_name. END add_dept.

your local declaration overrides the global declaration. FUNCTION TO_CHAR FUNCTION TO_CHAR FUNCTION TO_CHAR FUNCTION TO_CHAR VARCHAR2.Overloading: Example Entry Level Technology Program  Most built-in functions are overloaded.  For example. NUMBER. 27 of 1 Satyam Learning Center PL/SQL . P2 VARCHAR2) RETURN If you redeclare a built-in subprogram in a PL/SQL program. see the TO_CHAR function of the STANDARD package. P2 VARCHAR2) RETURN VARCHAR2. DATE. (p1 (p2 (p1 (p1 DATE) RETURN VARCHAR2. NUMBER) RETURN VARCHAR2.

Entry Level Technology Program Creating Database Triggers Satyam Learning Center PL/SQL 28 of 1 .

Objectives Entry Level Technology Program After completing this lesson. you should be able to do the following:  Describe different types of triggers  Describe database triggers and their use  Create database triggers  Describe database trigger firing rules  Remove database triggers Satyam Learning Center PL/SQL 29 of 1 .

schema. view.Types of Triggers Entry Level Technology Program A trigger:  Is a PL/SQL block or a PL/SQL procedure associated with a table. or the database  Executes implicitly whenever a particular event takes place  Can be either:  Application trigger: Fires whenever an event occurs with a particular application  Database trigger: Fires whenever a data event (such as DML) or system event (such as logon or shutdown) occurs on a schema or database Satyam Learning Center PL/SQL 30 of 1 .

which may be difficult to maintain in large applications. if the PL/SQL code is very lengthy. Satyam Learning Center PL/SQL 31 of 1 .Entry Level Technology Program Guidelines for Designing Triggers  Design triggers to:  Perform related actions  Centralize global operations  Do not design triggers:  Where functionality is already built into the Oracle server  That duplicate other triggers  Create stored procedures and invoke them in a trigger.  The excessive use of triggers can result in complex interdependencies.

EMPLOYEES table CHECK_SAL trigger … Satyam Learning Center PL/SQL 32 of 1 .Database Trigger: Example Entry Level Technology Program Application INSERT INTO EMPLOYEES . .. .

AFTER  For view: INSTEAD OF  Triggering event: INSERT. view  Trigger type: Row or statement  WHEN clause: Restricting condition  Trigger body: PL/SQL block Satyam Learning Center PL/SQL 33 of 1 . UPDATE. or DELETE  Table name: On table.Creating DML Triggers Entry Level Technology Program A triggering statement contains:  Trigger timing  For table: BEFORE.

 AFTER: Execute the trigger body after the triggering DML event on a table.DML Trigger Components Entry Level Technology Program Trigger timing: When should the trigger fire?  BEFORE: Execute the trigger body before the triggering DML event on a table.  INSTEAD OF: Execute the trigger body instead of the triggering statement. This is used for views that are not otherwise modifiable. Satyam Learning Center PL/SQL 34 of 1 .

DML Trigger Components Entry Level Technology Program Triggering user event: Which DML statement causes the trigger to execute? You can use any of the following:  INSERT  UPDATE  DELETE Satyam Learning Center PL/SQL 35 of 1 .

even if no rows are affected at all. Satyam Learning Center PL/SQL 36 of 1 . This is the default. A row trigger is not executed if the triggering event affects no rows. A statement trigger fires once.DML Trigger Components Entry Level Technology Program Trigger type: Should the trigger body execute for each row the statement affects or only once?  Statement: The trigger body executes once for the triggering event.  Row: The trigger body executes once for each row affected by the triggering event.

DML Trigger Components Entry Level Technology Program Trigger body: What action should the trigger perform? The trigger body is a PL/SQL block or a call to a procedure. Satyam Learning Center PL/SQL 37 of 1 .

2400). location_id) VALUES (400.Firing Sequence Entry Level Technology Program Use the following firing sequence for a trigger on a table. Triggering action BEFORE statement trigger … BEFORE row trigger AFTER row trigger AFTER statement trigger Satyam Learning Center PL/SQL 38 of 1 . when a single row is manipulated: DML statement INSERT INTO departments (department_id. 'CONSULTING'. department_name.

.. AFTER statement trigger Satyam Learning Center PL/SQL 39 of 1 .Firing Sequence Entry Level Technology Program Use the following firing sequence for a trigger on a table.1 WHERE department_id = 30... BEFORE row trigger AFTER row trigger . BEFORE statement trigger BEFORE row trigger AFTER row trigger . when many rows are manipulated: UPDATE employees SET salary = salary * 1.

Entry Level Technology Program Syntax for Creating DML Statement Triggers Syntax: CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_name trigger_body Note: Trigger names must be unique with respect to other triggers in the same schema. Satyam Learning Center PL/SQL 40 of 1 .

'SUN')) OR (TO_CHAR(SYSDATE.'DY') IN ('SAT'. END IF.'HH24:MI') NOT BETWEEN '08:00' AND '18:00') THEN RAISE_APPLICATION_ERROR (-20500.Entry Level Technology Program Creating DML Statement Triggers Example: CREATE OR REPLACE TRIGGER secure_emp BEFORE INSERT ON employees BEGIN IF (TO_CHAR(SYSDATE.').'You may insert into EMPLOYEES table only during business hours. / Satyam Learning Center PL/SQL 41 of 1 . END.

'RSMITH'. 4500.Testing SECURE_EMP Entry Level Technology Program INSERT INTO employees (employee_id. 60). 'IT_PROG'. email. hire_date. Satyam Learning Center PL/SQL 42 of 1 . department_id) VALUES (300. 'Smith'. last_name. 'Rob'. salary. SYSDATE. job_id. first_name.

'You may update EMPLOYEES table only during normal hours.').'You may insert into EMPLOYEES table only during business hours. 'HH24') NOT BETWEEN '08' AND '18') THEN IF DELETING THEN RAISE_APPLICATION_ERROR (-20502.'You may update SALARY only during business hours.'DY') IN ('SAT'. PL/SQL 43 of 1 Satyam Learning Center .'You may delete from EMPLOYEES table only during business hours.'). ELSIF UPDATING ('SALARY') THEN RAISE_APPLICATION_ERROR (-20503.Using Conditional Predicates Entry Level Technology Program CREATE OR REPLACE TRIGGER secure_emp BEFORE INSERT OR UPDATE OR DELETE ON employees BEGIN IF (TO_CHAR (SYSDATE.'SUN')) OR (TO_CHAR (SYSDATE. END IF.'). END IF. ELSIF INSERTING THEN RAISE_APPLICATION_ERROR (-20500. END.'). ELSE RAISE_APPLICATION_ERROR (-20504.

Satyam Learning Center PL/SQL 44 of 1 .Creating a DML Row Trigger Entry Level Technology Program Syntax: CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_name [REFERENCING OLD AS old | NEW AS new] FOR EACH ROW [WHEN (condition)] trigger_body OLD refers to the table and NEW refers to the shadow page.

job_id IN ('AD_PRES'. 'AD_VP')) AND :NEW. END. / Satyam Learning Center PL/SQL 45 of 1 .salary > 15000 THEN RAISE_APPLICATION_ERROR (-20202. END IF.'Employee cannot earn this amount').Creating DML Row Triggers Entry Level Technology Program CREATE OR REPLACE TRIGGER restrict_salary BEFORE INSERT OR UPDATE OF salary ON employees FOR EACH ROW BEGIN IF NOT (:NEW.

:NEW.last_name. SYSDATE. END. new_salary) VALUES (USER.employee_id.last_name. :NEW.salary. :NEW. old_title.job_id. :OLD. new_title. old_last_name.job_id. new_last_name. timestamp.salary ). :OLD.Using OLD and NEW Qualifiers Entry Level Technology Program CREATE OR REPLACE TRIGGER audit_emp_values AFTER DELETE OR INSERT OR UPDATE ON employees FOR EACH ROW BEGIN INSERT INTO audit_emp_table (user_name. :OLD. id. :OLD. / Satyam Learning Center PL/SQL 46 of 1 . old_salary.

commission_pct IS NULL THEN :NEW.job_id = 'SA_REP') BEGIN IF INSERTING THEN :NEW.commission_pct := 0. / Satyam Learning Center PL/SQL 47 of 1 . ELSE :NEW.commission_pct := :OLD. ELSIF :OLD.commission_pct + 0.Restricting a Row Trigger Entry Level Technology Program CREATE OR REPLACE TRIGGER derive_commission_pct BEFORE INSERT OR UPDATE OF salary ON employees FOR EACH ROW WHEN (NEW. END.commission_pct := 0.05. END IF.

INSTEAD OF Trigger INSERT TABLE1 MY_VIEW UPDATE TABLE2 Satyam Learning Center PL/SQL 48 of 1 . . .INSTEAD OF Triggers Entry Level Technology Program Application INSERT INTO my_view ..

Entry Level Technology Program Creating an INSTEAD OF Trigger Syntax: CREATE [OR REPLACE] TRIGGER trigger_name INSTEAD OF event1 [OR event2 OR event3] ON view_name [REFERENCING OLD AS old | NEW AS new] [FOR EACH ROW] trigger_body Satyam Learning Center PL/SQL 49 of 1 .

'HR_MAN '). ) VALUES(9001.. INSTEAD OF INSERT into EMP_DETAILS … Satyam Learning Center PL/SQL 50 of 1 .mail.3000.'ABBOTT'. .'abbott.com'.10.Entry Level Technology Program Creating an INSTEAD OF Trigger 1 INSERT into EMP_DETAILS that is based on EMPLOYEES and DEPARTMENTS tables INSERT INTO emp_details(employee_id..

'ABBOTT'.3000. INSTEAD OF INSERT into EMP_DETAILS … 2 INSERT into NEW_EMPS 3 UPDATE NEW_DEPTS … Satyam Learning Center PL/SQL … 51 of 1 .10...'abbott.Entry Level Technology Program Creating an INSTEAD OF Trigger INSERT into EMP_DETAILS that is based on EMPLOYEES and DEPARTMENTS tables 1 INSERT INTO emp_details(employee_id.'HR_MAN ').com'. .mail. ) VALUES(9001.

Entry Level Technology Program Differentiating Between Database Triggers and Stored Procedures Procedures Defined with CREATE PROCEDURE Data dictionary contains source code in USER_SOURCE Explicitly invoked COMMIT. SAVEPOINT. and ROLLBACK are allowed Triggers Defined with CREATE TRIGGER Data dictionary contains source code in USER_TRIGGERS Implicitly invoked COMMIT. SAVEPOINT. and ROLLBACK are not allowed Satyam Learning Center PL/SQL 52 of 1 .

Example: DROP TRIGGER secure_emp. use the DROP TRIGGER syntax: DROP TRIGGER trigger_name. Note: All triggers on a table are dropped when the table is dropped. Satyam Learning Center PL/SQL 53 of 1 .DROP TRIGGER Syntax Entry Level Technology Program To remove a trigger from the database.

functions and packages d) Write a trigger to update the stock automatically when customer orders an item or supermarket is getting the stock from dealer.Exercise Entry Level Technology Program  Write a program to maintain the activities of supermarket 1) Supermarket maintaining various items itemno itemname stock 2) Customer ordering items or supermarket is getting the stock from dealers. Satyam Learning Center PL/SQL 54 of 1 .  Trnno itemno trndate trntype quantity a) trntype should be only receipt / issue c) write the program using procedures.