61
Bordoloi and Bordoloi and Bock Bock Chapter 13 : Chapter 13 : PROCEDURES, PROCEDURES, FUNCTIONS, PACKAGES, and FUNCTIONS, PACKAGES, and TRIGGERS TRIGGERS

Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Embed Size (px)

DESCRIPTION

Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS. Learning Objectives. Create and drop procedures – includes passing parameters and values. Create and drop functions – includes returning values. - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Chapter 13 :Chapter 13 : PROCEDURES, PROCEDURES, FUNCTIONS, PACKAGES, and FUNCTIONS, PACKAGES, and

TRIGGERSTRIGGERS

Page 2: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Learning ObjectivesLearning Objectives• Create and drop procedures – includes passing Create and drop procedures – includes passing

parameters and values.parameters and values.

• Create and drop functions – includes returning Create and drop functions – includes returning values.values.

• Create package specifications, package bodies, Create package specifications, package bodies, stored, packages, cursor processing in stored, packages, cursor processing in packages, and calling stored packages.packages, and calling stored packages.

• Create, alter, drop, enable, and disable triggers Create, alter, drop, enable, and disable triggers – includes before and after triggers.– includes before and after triggers.

Page 3: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Procedures and FunctionsProcedures and Functions

• Oracle subprograms – includes both procedures Oracle subprograms – includes both procedures and functions.and functions.

• Both procedures and functions:Both procedures and functions:– Can be programmed to perform a data processing task. Can be programmed to perform a data processing task. – Are named PL/SQL blocks, and both can be coded to Are named PL/SQL blocks, and both can be coded to

take parameters to generalize the code. take parameters to generalize the code. – Can be written with declarative, executable, and Can be written with declarative, executable, and

exception sections. exception sections. • Functions are typically coded to perform some Functions are typically coded to perform some

type of calculation. type of calculation. • Primary difference – procedures are called with Primary difference – procedures are called with

PL/SQL statements while functions are called as PL/SQL statements while functions are called as part of an expression. part of an expression.

Page 4: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Procedures and FunctionsProcedures and Functions

• Procedures and functions:Procedures and functions:– Normally stored in the database within package Normally stored in the database within package

specifications – a package is a sort of wrapper for a specifications – a package is a sort of wrapper for a group of named blocks. group of named blocks.

– Can be stored as individual database objects. Can be stored as individual database objects. – Are parsed and compiled at the time they are stored. Are parsed and compiled at the time they are stored. – Compiled objects execute faster than nonprocedural Compiled objects execute faster than nonprocedural

SQL scripts because nonprocedural scripts require extra SQL scripts because nonprocedural scripts require extra time for compilation. time for compilation.

– Can be invoked from most Oracle tools like SQL*Plus, Can be invoked from most Oracle tools like SQL*Plus, and from other programming languages like C++ and and from other programming languages like C++ and JAVA. JAVA.

Page 5: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Benefits of Subprograms• Improved data securityImproved data security – controls access to database objects – controls access to database objects

while enabling non-privileged application users to access just while enabling non-privileged application users to access just the data needed. the data needed.

• Improved data integrity Improved data integrity – related actions on database tables are – related actions on database tables are performed as a unit enforcing transaction integrity – all updates performed as a unit enforcing transaction integrity – all updates are executed or none are executed.are executed or none are executed.

• Improved application performanceImproved application performance – avoids reparsing objects used by multiple users through the use of shared SQL for Oracle – reduces number of database calls thus reducing network traffic.

• Improved maintenanceImproved maintenance – procedures and functions that perform and functions that perform common tasks can be modified without having to directly work common tasks can be modified without having to directly work on multiple applications that may call these common procedures on multiple applications that may call these common procedures and functions – this approach eliminates duplicate testing. and functions – this approach eliminates duplicate testing.

Page 6: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

ProceduresProcedures

• Procedures are named PL/SQL blocks. Procedures are named PL/SQL blocks.

• Created/owned by a particular schemaCreated/owned by a particular schema

• Privilege to execute a specific procedure can be Privilege to execute a specific procedure can be granted to or revoked from application users in granted to or revoked from application users in order to control data access. order to control data access.

• Requires CREATE PROCEDURE (to create in Requires CREATE PROCEDURE (to create in your schema) or CREATE ANY PROCEDURE your schema) or CREATE ANY PROCEDURE privilege (to create in other schemas).privilege (to create in other schemas).

Page 7: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

CREATE PROCEDURE SyntaxCREATE PROCEDURE SyntaxCREATE [OR REPLACE] PROCEDURE <procedure_name>

(<parameter1_name> <mode> <data type>, <parameter2_name> <mode> <data type>, ...) {AS|IS}

<Variable declarations>BEGIN Executable statements[EXCEPTION Exception handlers]END <optional procedure name>;

• Unique procedure name is required.• OR REPLACE clause facilitates testing.• Parameters are optional – enclosed in parentheses when used.• AS or IS keyword is used – both work identically.• Procedure variables are declared prior to the BEGIN keyword.• DECLARE keyword is NOT used in named procedure.

Page 8: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Compiling and Showing ErrorsCompiling and Showing Errors

• To Compile/Load a procedure use either the “@” symbol or the To Compile/Load a procedure use either the “@” symbol or the START SQL command to compile the file. The START SQL command to compile the file. The <SQL <SQL filename>filename> parameter is the .sql file that contains the procedure parameter is the .sql file that contains the procedure to be compiled.to be compiled.

SQL>@<SQL filename> SQL>@<SQL filename> SQL>start <SQL filename>SQL>start <SQL filename>

• Filename does not need to be the same as the procedure name. Filename does not need to be the same as the procedure name. The .sql file only contains the procedure code. The .sql file only contains the procedure code.

• Compiled procedure is stored in the database, not the .sql file. Compiled procedure is stored in the database, not the .sql file. • Use SHOW ERRORS command if the procedure does not Use SHOW ERRORS command if the procedure does not

compile without errors. Use EXECUTE to run procedure. compile without errors. Use EXECUTE to run procedure. SQL> show errors;SQL> show errors;SQL> EXECUTE Insert_EmployeeSQL> EXECUTE Insert_Employee

Page 9: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

ParametersParameters• Both procedures and functions can take parameters. Both procedures and functions can take parameters. • Values passed as parameters to a procedure as arguments in a Values passed as parameters to a procedure as arguments in a

calling statement are termed calling statement are termed actual parametersactual parameters. . • The parameters in a procedure declaration are called The parameters in a procedure declaration are called formal formal

parametersparameters. . • The values stored in actual parameters are values passed to the The values stored in actual parameters are values passed to the

formal parameters – the formal parameters are like placeholders formal parameters – the formal parameters are like placeholders to store the incoming values. to store the incoming values.

• When a procedure completes, the actual parameters are When a procedure completes, the actual parameters are assigned the values of the formal parameters. assigned the values of the formal parameters.

• A formal parameter can have one of three possible modes: (1) A formal parameter can have one of three possible modes: (1) IN, (2), OUT, or (3) IN OUT. IN, (2), OUT, or (3) IN OUT.

Page 10: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Defining the IN, OUT, and IN OUT Defining the IN, OUT, and IN OUT Parameter ModesParameter Modes

• ININ – this – this parameter type is passed to a procedure as a read-only parameter type is passed to a procedure as a read-only value that cannot be changed within the procedure – this is the value that cannot be changed within the procedure – this is the default mode.default mode.

• OUTOUT – this parameter type is write-only, and can only appear on – this parameter type is write-only, and can only appear on the left side of an assignment statement in the procedure – it is the left side of an assignment statement in the procedure – it is assigned an initial value of NULL.assigned an initial value of NULL.

• IN OUTIN OUT – this parameter type combines both IN and OUT; a – this parameter type combines both IN and OUT; a parameter of this mode is passed to a procedure, and its value parameter of this mode is passed to a procedure, and its value can be changed within the procedure.can be changed within the procedure.

• If a procedure raises an exception, the formal parameter If a procedure raises an exception, the formal parameter values are not copied back to their corresponding actual values are not copied back to their corresponding actual parameters.parameters.

Page 11: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Parameter Constraint RestrictionsParameter Constraint Restrictions• Procedures do not allow specifying Procedures do not allow specifying a constraint on the a constraint on the

parameter data type. parameter data type. • Example: the following CREATE PROCEDURE Example: the following CREATE PROCEDURE

statement is not allowed because of the specification statement is not allowed because of the specification that constrains the that constrains the v_Variablev_Variable parameter to parameter to NUMBER(2). Instead use the general data type of NUMBER(2). Instead use the general data type of NUMBER.NUMBER.

/* Invalid constraint on parameter. *//* Invalid constraint on parameter. */CREATE OR REPLACE PROCEDURE proSample CREATE OR REPLACE PROCEDURE proSample (v_Variable NUMBER(2), ...) (v_Variable NUMBER(2), ...)

/* Valid parameter. *//* Valid parameter. */CREATE OR REPLACE PROCEDURE proSample CREATE OR REPLACE PROCEDURE proSample (v_Variable NUMBER, ...) (v_Variable NUMBER, ...)

Page 12: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.1 (1 of 2)Example 13.1 (1 of 2)

/* PL SQL Example 13.1 File: ch13-1.sql *//* PL SQL Example 13.1 File: ch13-1.sql */CREATE OR REPLACE PROCEDURE UpdateEquipment (CREATE OR REPLACE PROCEDURE UpdateEquipment ( p_EquipmentNumber IN Equipment.EquipmentNumberp_EquipmentNumber IN Equipment.EquipmentNumber

%TYPE,%TYPE, p_Description IN Equipment.Description%TYPE,p_Description IN Equipment.Description%TYPE, p_Cost IN Equipment.OriginalCost%TYPE,p_Cost IN Equipment.OriginalCost%TYPE, p_Quantity IN Equipment.QuantityAvailable%TYPE,p_Quantity IN Equipment.QuantityAvailable%TYPE, p_Project IN Equipment.ProjectNumber%TYPE )p_Project IN Equipment.ProjectNumber%TYPE )ASAS e_EquipmentNotFound EXCEPTION;e_EquipmentNotFound EXCEPTION; v_ErrorTEXT VARCHAR2(512);v_ErrorTEXT VARCHAR2(512);

Page 13: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.1 (2 of 2)Example 13.1 (2 of 2)BEGINBEGIN UPDATE Equipment SET Description = p_Description, UPDATE Equipment SET Description = p_Description, OriginalCost = p_Cost, QuantityAvailable = OriginalCost = p_Cost, QuantityAvailable = p_Quantity, ProjectNumber = p_Projectp_Quantity, ProjectNumber = p_Project WHERE EquipmentNumber = p_EquipmentNumber;WHERE EquipmentNumber = p_EquipmentNumber; IF SQL%ROWCOUNT = 0 THENIF SQL%ROWCOUNT = 0 THEN Raise e_EquipmentNotFound;Raise e_EquipmentNotFound; END IF;END IF;EXCEPTIONEXCEPTION WHEN e_EquipmentNotFound THENWHEN e_EquipmentNotFound THEN DBMS_OUTPUT.PUT_LINE ('Invalid Equipment Number: 'DBMS_OUTPUT.PUT_LINE ('Invalid Equipment Number: ' ||p_EquipmentNumber); ||p_EquipmentNumber); WHEN OTHERS THENWHEN OTHERS THEN v_ErrorText := SQLERRM;v_ErrorText := SQLERRM; DBMS_OUTPUT.PUT_LINE ('Unexpected error'DBMS_OUTPUT.PUT_LINE ('Unexpected error' ||v_ErrorText);||v_ErrorText);END UpdateEquipment; END UpdateEquipment; //

Page 14: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.2 – Calls procedure of 13.1Example 13.2 – Calls procedure of 13.1

/* PL SQL Example 13.2 File: ch13-2.sql *//* PL SQL Example 13.2 File: ch13-2.sql */DECLAREDECLARE v_EquipmentNumber Equipment.EquipmentNumber%TYPE v_EquipmentNumber Equipment.EquipmentNumber%TYPE := '5000';:= '5000'; v_Description Equipment.Description%TYPE v_Description Equipment.Description%TYPE := 'Printer';:= 'Printer'; v_Cost Equipment.OriginalCost%TYPE := 172.00;v_Cost Equipment.OriginalCost%TYPE := 172.00; v_Quantity Equipment.QuantityAvailable%TYPE := 2;v_Quantity Equipment.QuantityAvailable%TYPE := 2; v_Project Equipment.ProjectNumber%TYPE := 5;v_Project Equipment.ProjectNumber%TYPE := 5;BEGINBEGIN UpdateEquipment(v_EquipmentNumber, v_Description, UpdateEquipment(v_EquipmentNumber, v_Description, v_Cost, v_Quantity, v_Project);v_Cost, v_Quantity, v_Project);END; END; //

Page 15: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Points to Understand About Points to Understand About UpdateEquipmentUpdateEquipment Procedure Procedure

• There are several points that you need to understand about There are several points that you need to understand about calling a procedure and the use of parameters for this example. calling a procedure and the use of parameters for this example.

• The The UpdateEquipmentUpdateEquipment procedure is first created, compiled, and procedure is first created, compiled, and stored in the database as a compiled object.stored in the database as a compiled object.

• The actual parameters are declared within PL/SQL Example The actual parameters are declared within PL/SQL Example 13.2 and assigned values – the assigned values here merely 13.2 and assigned values – the assigned values here merely illustrate that the parameters would have values that are passed illustrate that the parameters would have values that are passed to the to the UpdateEquipmentUpdateEquipment procedure. procedure.

• The calling statement is a PL/SQL statement by itself and is not The calling statement is a PL/SQL statement by itself and is not part of an expression – control will pass from the calling part of an expression – control will pass from the calling statement to the first statement inside the procedure.statement to the first statement inside the procedure.

• Because the formal parameters in Because the formal parameters in UpdateEquipmentUpdateEquipment are all are all declared as mode IN, the values of these parameters cannot be declared as mode IN, the values of these parameters cannot be changed within the procedure.changed within the procedure.

Page 16: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.4 – Procedure with No ParametersExample 13.4 – Procedure with No Parameters

/* PL SQL Example 13.4 File: ch13-4.sql *//* PL SQL Example 13.4 File: ch13-4.sql */CREATE OR REPLACE PROCEDURE DisplaySalary ISCREATE OR REPLACE PROCEDURE DisplaySalary IS -- create local variable with required constraint-- create local variable with required constraint temp_Salary NUMBER(10,2); temp_Salary NUMBER(10,2); BEGINBEGIN SELECT Salary INTO temp_Salary FROM EmployeeSELECT Salary INTO temp_Salary FROM Employee WHERE EmployeeID = '01885';WHERE EmployeeID = '01885'; IF temp_Salary > 15000 THENIF temp_Salary > 15000 THEN DBMS_OUTPUT.PUT_LINE ('Salary > 15,000.');DBMS_OUTPUT.PUT_LINE ('Salary > 15,000.'); ELSEELSE DBMS_OUTPUT.PUT_LINE ('Salary < 15,000.');DBMS_OUTPUT.PUT_LINE ('Salary < 15,000.'); END IF;END IF;EXCEPTIONEXCEPTION WHEN NO_DATA_FOUND THENWHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ('Employee not found.');DBMS_OUTPUT.PUT_LINE ('Employee not found.');END DisplaySalary;END DisplaySalary;//

Page 17: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Executing Executing DisplaySalaryDisplaySalary Procedure Procedure

SQL> @ch13-4.sqlSQL> @ch13-4.sql

Procedure created.Procedure created.

SQL> SQL> exec DisplaySalaryexec DisplaySalary

Salary > 15,000.Salary > 15,000.

PL/SQL procedure successfully completed.PL/SQL procedure successfully completed.

Page 18: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.5 – Passing IN and OUT ParametersExample 13.5 – Passing IN and OUT Parameters

/* PL SQL Example 13.5 File: ch13-5.sql *//* PL SQL Example 13.5 File: ch13-5.sql */CREATE OR REPLACE PROCEDURE DisplaySalary2(p_EmployeeIDCREATE OR REPLACE PROCEDURE DisplaySalary2(p_EmployeeID IN CHAR, p_Salary OUT NUMBER) ISIN CHAR, p_Salary OUT NUMBER) IS v_Salary NUMBER(10,2);v_Salary NUMBER(10,2);BEGINBEGIN SELECT Salary INTO v_Salary FROM EmployeeSELECT Salary INTO v_Salary FROM Employee WHERE EmployeeID = p_EmployeeID;WHERE EmployeeID = p_EmployeeID; IF v_Salary > 15000 THENIF v_Salary > 15000 THEN DBMS_OUTPUT.PUT_LINE ('Salary > 15,000.');DBMS_OUTPUT.PUT_LINE ('Salary > 15,000.'); ELSEELSE DBMS_OUTPUT.PUT_LINE ('Salary <= 15,000.');DBMS_OUTPUT.PUT_LINE ('Salary <= 15,000.'); END IF;END IF; p_Salary := v_Salary; p_Salary := v_Salary; EXCEPTIONEXCEPTION WHEN NO_DATA_FOUND THENWHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ('Employee not found.'); DBMS_OUTPUT.PUT_LINE ('Employee not found.'); END DisplaySalary2;END DisplaySalary2;

Page 19: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.6 – Calling Example 13.6 – Calling DisplaySalary2DisplaySalary2

/* PL SQL Example 13.6 File: ch13-6.sql *//* PL SQL Example 13.6 File: ch13-6.sql */DECLAREDECLARE v_SalaryOutput NUMBER := 0;v_SalaryOutput NUMBER := 0;BEGINBEGIN -- call the procedure-- call the procedure DisplaySalary2('01885', v_SalaryOutput);DisplaySalary2('01885', v_SalaryOutput); -- display value of salary after the call-- display value of salary after the call DBMS_OUTPUT.PUT_LINE ('Actual salary: ' DBMS_OUTPUT.PUT_LINE ('Actual salary: ' ||TO_CHAR(v_SalaryOutput));||TO_CHAR(v_SalaryOutput));END;END;//

Salary > 15,000.Salary > 15,000.Actual salary: 16250Actual salary: 16250PL/SQL procedure successfully completed.PL/SQL procedure successfully completed.

Page 20: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.7 – Using Bind VariablesExample 13.7 – Using Bind Variables• Another approach to test a procedure. This approach uses a Another approach to test a procedure. This approach uses a

bind variablebind variable in Oracle. in Oracle. • A bind variable is a variable created at the SQL*Plus prompt A bind variable is a variable created at the SQL*Plus prompt

that is used to reference variables in PL/SQL subprograms. that is used to reference variables in PL/SQL subprograms. • A bind variable used in this fashion must be prefixed with a A bind variable used in this fashion must be prefixed with a

colon “:” – this syntax is required.colon “:” – this syntax is required.

/* PL SQL Example 13.7 *//* PL SQL Example 13.7 */SQL> var v_SalaryOutput NUMBER;SQL> var v_SalaryOutput NUMBER;SQL> EXEC DisplaySalary2('01885', SQL> EXEC DisplaySalary2('01885', :v_SalaryOutput:v_SalaryOutput););Salary > 15,000.Salary > 15,000.PL/SQL procedure successfully completed.PL/SQL procedure successfully completed.SQL> PRINT v_SalaryOutput;SQL> PRINT v_SalaryOutput;

V_SALARYOUTPUTV_SALARYOUTPUT---------------------------- 1625016250

Page 21: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Dropping a ProcedureDropping a Procedure

• The SQL statement to drop a procedure is the The SQL statement to drop a procedure is the straight-forward DROP PROCEDURE straight-forward DROP PROCEDURE <procedureName> command. <procedureName> command.

• This is a data definition language (DDL) This is a data definition language (DDL) command, and so an implicit commit executes command, and so an implicit commit executes prior to and immediately after the command.prior to and immediately after the command.

SQL> DROP PROCEDURE DisplaySalary2;SQL> DROP PROCEDURE DisplaySalary2;

Procedure dropped.Procedure dropped.

Page 22: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Create Function Syntax• Like a procedure, a function can accept multiple parameters, Like a procedure, a function can accept multiple parameters,

and the data type of the return value must be declared in the and the data type of the return value must be declared in the header of the function. header of the function. CREATE [OR REPLACE] FUNCTION <function_name> CREATE [OR REPLACE] FUNCTION <function_name>

(<parameter1_name> <mode> <data type>, (<parameter1_name> <mode> <data type>, <parameter2_name> <mode> <data type>, ...) <parameter2_name> <mode> <data type>, ...) RETURN <function return value data type> {AS|IS}RETURN <function return value data type> {AS|IS} <Variable declarations><Variable declarations>BEGINBEGIN Executable CommandsExecutable Commands RETURN (return_value);RETURN (return_value); . . .. . .[EXCEPTION[EXCEPTION Exception handlers]Exception handlers]END;END;

• The general syntax of the RETURN statement is:The general syntax of the RETURN statement is:RETURN <expression>;RETURN <expression>;

Page 23: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.8 – No Parameters in FunctionExample 13.8 – No Parameters in Function /* PL SQL Example 13.8 /* PL SQL Example 13.8 File: ch13-8.sql */File: ch13-8.sql */CREATE OR REPLACE FUNCTION RetrieveSalaryCREATE OR REPLACE FUNCTION RetrieveSalary RETURN NUMBERRETURN NUMBERISIS v_Salary NUMBER(10,2);v_Salary NUMBER(10,2);BEGIN BEGIN SELECT Salary INTO v_Salary SELECT Salary INTO v_Salary FROM Employee FROM Employee WHERE EmployeeID = '01885';WHERE EmployeeID = '01885'; RETURN v_Salary;RETURN v_Salary;END RetrieveSalary;END RetrieveSalary;//

Page 24: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.9 – Testing Example 13.9 – Testing RetrieveSalaryRetrieveSalary FunctionFunction

/* PL SQL Example 13.9 *//* PL SQL Example 13.9 */SQL> @RetrieveSalarySQL> @RetrieveSalaryFunction created.Function created.SQL> var v_SalaryOutput NUMBER;SQL> var v_SalaryOutput NUMBER;SQL> EXEC :v_SalaryOutput := SQL> EXEC :v_SalaryOutput := RetrieveSalaryRetrieveSalary;;

PL/SQL procedure successfully completed.PL/SQL procedure successfully completed.

SQL> print v_SalaryOutput;SQL> print v_SalaryOutput;V_SALARYOUTPUTV_SALARYOUTPUT---------------------------- 1625016250

Page 25: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.9 (1 of 2)– Function with Example 13.9 (1 of 2)– Function with ParameterParameter• PL/SQL Example 13.9 illustrates a function that has a single PL/SQL Example 13.9 illustrates a function that has a single

IN parameter and that returns a VARCHAR2 data type. IN parameter and that returns a VARCHAR2 data type.

/* PL SQL Example 13.9 File: ch13-9.sql *//* PL SQL Example 13.9 File: ch13-9.sql */CREATE OR REPLACE FUNCTION FullName (p_EmployeeID IN CREATE OR REPLACE FUNCTION FullName (p_EmployeeID IN employee.EmployeeID%TYPE) employee.EmployeeID%TYPE) RETURN VARCHAR2 ISRETURN VARCHAR2 IS v_FullName VARCHAR2(100);v_FullName VARCHAR2(100); v_FirstName employee.FirstName%TYPE;v_FirstName employee.FirstName%TYPE; v_MiddleName employee.MiddleName%TYPE;v_MiddleName employee.MiddleName%TYPE; v_LastName employee.LastName%TYPE;v_LastName employee.LastName%TYPE;BEGINBEGIN SELECT FirstName, MiddleName, LastName INTOSELECT FirstName, MiddleName, LastName INTO v_FirstName, v_MiddleName, v_LastNamev_FirstName, v_MiddleName, v_LastName FROM EmployeeFROM Employee WHERE EmployeeID = p_EmployeeID;WHERE EmployeeID = p_EmployeeID;

Page 26: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.9 (1 of 2)– Function with Example 13.9 (1 of 2)– Function with ParameterParameter

-- Store last name, comma and blank and first name -- Store last name, comma and blank and first name to variableto variable

v_FullName := v_LastName||', '||v_FirstName;v_FullName := v_LastName||', '||v_FirstName; -- Check for existence of a middle name-- Check for existence of a middle name IF LENGTH(v_MiddleName) > 0 THENIF LENGTH(v_MiddleName) > 0 THEN v_FullName := v_FullName|| ' ' v_FullName := v_FullName|| ' ' ||SUBSTR(v_MiddleName,1,1)||'.';||SUBSTR(v_MiddleName,1,1)||'.'; END IF; END IF; RETURN v_FullName;RETURN v_FullName;END FullName;END FullName;//

Page 27: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.10 – Testing Example 13.10 – Testing FullNameFullName Function Function

• A simple SELECT statement executed within A simple SELECT statement executed within SQL*Plus can return the full name for any SQL*Plus can return the full name for any employee identifier value as shown in PL/SQL employee identifier value as shown in PL/SQL Example 13.10. Example 13.10.

/* PL SQL Example 13.10 *//* PL SQL Example 13.10 */SQL> SELECT FullName('01885') SQL> SELECT FullName('01885') 2 FROM Employee2 FROM Employee 3 WHERE EmployeeID = '01885';3 WHERE EmployeeID = '01885';

FULLNAME('01885')FULLNAME('01885')----------------------------------------------------------------------Bock, Douglas B.Bock, Douglas B.

Page 28: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.11 – Testing Example 13.11 – Testing FullNameFullName Function Function

/* PL SQL Example 13.11 *//* PL SQL Example 13.11 */SQL> SELECT FullName(EmployeeID)SQL> SELECT FullName(EmployeeID) 2 FROM Employee2 FROM Employee 3 ORDER BY FullName(EmployeeID);3 ORDER BY FullName(EmployeeID);

FULLNAME(EMPLOYEEID)FULLNAME(EMPLOYEEID)--------------------------------------------------------------------------Adams, Adam A.Adams, Adam A.Barlow, William A.Barlow, William A.Becker, Robert B.Becker, Robert B.Becker, Roberta G.Becker, Roberta G.Bock, Douglas B.Bock, Douglas B.... more rows will display... more rows will display

Page 29: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Dropping a FunctionDropping a Function • As with the DROP PROCEDURE statement, the As with the DROP PROCEDURE statement, the

DROP FUNCTION <functionName> is also DROP FUNCTION <functionName> is also straight-forward. straight-forward.

• As with DROP PROCEDURE, the DROP As with DROP PROCEDURE, the DROP FUNCTION statement is a DDL command that FUNCTION statement is a DDL command that causes execution of an implicit commit prior to causes execution of an implicit commit prior to and immediately after the command.and immediately after the command.

SQL> DROP FUNCTION FullName;SQL> DROP FUNCTION FullName;

Function dropped.Function dropped.

Page 30: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

PACKAGESPACKAGES

• A A packagepackage is a collection of PL/SQL objects is a collection of PL/SQL objects grouped together under one package name. grouped together under one package name.

• Packages provide a means to collect related Packages provide a means to collect related procedures, functions, cursors, declarations, procedures, functions, cursors, declarations, types, and variables into a single, named types, and variables into a single, named database object that is more flexible than the database object that is more flexible than the related database objects are by themselves.related database objects are by themselves.

• Package variables – can be referenced in any Package variables – can be referenced in any procedure, function, (other object) defined procedure, function, (other object) defined within a package.within a package.

Page 31: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Package Specification and ScopePackage Specification and Scope• A package consists of a package specification and a package A package consists of a package specification and a package

body. body. – The The package specificationpackage specification, also called the package header., also called the package header.– Declares global variables, cursors, exceptions, procedures, and functions Declares global variables, cursors, exceptions, procedures, and functions

that can be called or accessed by other program units. that can be called or accessed by other program units. – A package specification must be a uniquely named database object. A package specification must be a uniquely named database object. – Elements of a package can declared in any order. If element “A” is Elements of a package can declared in any order. If element “A” is

referenced by another element, then element “A” must be declared before referenced by another element, then element “A” must be declared before it is referenced by another element. For example, a variable referenced it is referenced by another element. For example, a variable referenced by a cursor must be declared before it is used by the cursor. by a cursor must be declared before it is used by the cursor.

• Declarations of subprograms must be forward declarations. Declarations of subprograms must be forward declarations. – This means the declaration only includes the subprogram name and This means the declaration only includes the subprogram name and

arguments, but does not include the actual program code. arguments, but does not include the actual program code.

Page 32: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Create Package SyntaxCreate Package Syntax• Basically, a package is a named declaration section. Basically, a package is a named declaration section.

– Any object that can be declared in a PL/SQL block can be Any object that can be declared in a PL/SQL block can be declared in a package. declared in a package.

– Use the CREATE OR REPLACE PACKAGE clause. Use the CREATE OR REPLACE PACKAGE clause. – Include the specification of each named PL/SQL block Include the specification of each named PL/SQL block

header that will be public within the package. header that will be public within the package. – Procedures, functions, cursors, and variables that are Procedures, functions, cursors, and variables that are

declared in the package specification are declared in the package specification are globalglobal. . • The basic syntax for a package is:The basic syntax for a package is:

CREATE [OR REPLACE PACKAGE[ <package name> {AS|IS}CREATE [OR REPLACE PACKAGE[ <package name> {AS|IS} <variable declarations>;<variable declarations>; <cursor declarations>;<cursor declarations>; <procedure and function declarations>;<procedure and function declarations>;END <package name>;END <package name>;

Page 33: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Declaring Procedures and Functions Declaring Procedures and Functions within a Packagewithin a Package

• To declare a procedure in a package – specify the To declare a procedure in a package – specify the procedure name, followed by the parameters and procedure name, followed by the parameters and variable types: variable types:

PROCEDURE <procedure_name> (param1 param1datatype, PROCEDURE <procedure_name> (param1 param1datatype,

param2 param2datatype, ...);param2 param2datatype, ...);

• To declare a function in a package, you must specify To declare a function in a package, you must specify the function name, parameters and return variable type:the function name, parameters and return variable type:

FUNCTION <function_name> (param1 param1datatype, FUNCTION <function_name> (param1 param1datatype,

param2 param2datatype, ...)param2 param2datatype, ...)

RETURN <return data type>;RETURN <return data type>;

Page 34: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Package BodyPackage Body

• Contains the code for the subprograms and other Contains the code for the subprograms and other constructs, such as exceptions, declared in the package constructs, such as exceptions, declared in the package specification. specification.

• Is optional – a package that contains only variable Is optional – a package that contains only variable declarations, cursors, and the like, but no procedure or declarations, cursors, and the like, but no procedure or function declarations does not require a package body. function declarations does not require a package body.

• Any subprograms declared in a package must be coded Any subprograms declared in a package must be coded completely in the package body. The procedure and completely in the package body. The procedure and function specifications of the package body must match function specifications of the package body must match the package declarations including subprogram names, the package declarations including subprogram names, parameter names, and parameter modes.parameter names, and parameter modes.

Page 35: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Create Package Body SyntaxCreate Package Body Syntax

• Use the CREATE OR REPLACE Use the CREATE OR REPLACE PACKAGE BODY clause to create a PACKAGE BODY clause to create a package body. The basic syntax is:package body. The basic syntax is:

CREATE [OR REPLACE] PACKAGE BODY <package CREATE [OR REPLACE] PACKAGE BODY <package name> ASname> AS

<cursor specifications><cursor specifications>

<subprogram specifications and code><subprogram specifications and code>

END <package name>;END <package name>;

Page 36: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.12 – Example PackageExample 13.12 – Example Package

/* PL SQL Example 13.12 File: ch13-12.sql *//* PL SQL Example 13.12 File: ch13-12.sql */CREATE OR REPLACE PACKAGE ManageEmployee ASCREATE OR REPLACE PACKAGE ManageEmployee AS -- Global variable declarations go here-- Global variable declarations go here -- Procedure to find employees-- Procedure to find employees PROCEDURE FindEmployee(PROCEDURE FindEmployee( emp_ID IN employee.EmployeeID%TYPE,emp_ID IN employee.EmployeeID%TYPE, emp_FirstName OUT employee.FirstName%TYPE,emp_FirstName OUT employee.FirstName%TYPE, emp_LastName OUT employee.LastName%TYPE);emp_LastName OUT employee.LastName%TYPE); -- Exception raised by FindEmployee-- Exception raised by FindEmployee e_EmployeeIDNotFound EXCEPTION;e_EmployeeIDNotFound EXCEPTION; -- Function to determine if employee identifier is -- Function to determine if employee identifier is

validvalid FUNCTION GoodIdentifier(FUNCTION GoodIdentifier( emp_ID IN employee.EmployeeID%TYPE)emp_ID IN employee.EmployeeID%TYPE) RETURN BOOLEAN;RETURN BOOLEAN;END ManageEmployee;END ManageEmployee;//

Page 37: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.13 (1 of 2) – Package BodyExample 13.13 (1 of 2) – Package Body/* PL SQL Example 13.13 File: ch13-13.sql *//* PL SQL Example 13.13 File: ch13-13.sql */CREATE OR REPLACE PACKAGE BODY ManageEmployee ASCREATE OR REPLACE PACKAGE BODY ManageEmployee AS -- Procedure to find employees-- Procedure to find employees PROCEDURE FindEmployee(PROCEDURE FindEmployee( emp_ID IN employee.EmployeeID%TYPE,emp_ID IN employee.EmployeeID%TYPE, emp_FirstName OUT employee.FirstName%TYPE,emp_FirstName OUT employee.FirstName%TYPE, emp_LastName OUT employee.LastName%TYPE ) ASemp_LastName OUT employee.LastName%TYPE ) AS BEGINBEGIN SELECT FirstName, LastNameSELECT FirstName, LastName INTO emp_FirstName, emp_LastNameINTO emp_FirstName, emp_LastName FROM EmployeeFROM Employee WHERE EmployeeID = emp_ID;WHERE EmployeeID = emp_ID; -- Check for existence of employee-- Check for existence of employee IF SQL%ROWCOUNT = 0 THENIF SQL%ROWCOUNT = 0 THEN RAISE e_EmployeeIDNotFound;RAISE e_EmployeeIDNotFound; END IF;END IF; END FindEmployee;END FindEmployee;

Page 38: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.13 (2 of 2) – Package BodyExample 13.13 (2 of 2) – Package Body

-- Function to determine if employee identifier is valid-- Function to determine if employee identifier is valid FUNCTION GoodIdentifier(FUNCTION GoodIdentifier( emp_ID IN employee.EmployeeID%TYPE)emp_ID IN employee.EmployeeID%TYPE) RETURN BOOLEANRETURN BOOLEAN ISIS v_ID_Count NUMBER;v_ID_Count NUMBER; BEGINBEGIN SELECT COUNT(*) INTO v_ID_CountSELECT COUNT(*) INTO v_ID_Count FROM EmployeeFROM Employee WHERE EmployeeID = emp_ID;WHERE EmployeeID = emp_ID;

-- return TRUE if v_ID_COUNT is 1-- return TRUE if v_ID_COUNT is 1 RETURN (1 = v_ID_Count);RETURN (1 = v_ID_Count); EXCEPTIONEXCEPTION WHEN OTHERS THENWHEN OTHERS THEN RETURN FALSE;RETURN FALSE; END GoodIdentifier;END GoodIdentifier;END ManageEmployee;END ManageEmployee;

Page 39: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.14 – Calling Package ProcedureExample 13.14 – Calling Package Procedure/* PL SQL Example 13.14 /* PL SQL Example 13.14 File: ch13-14.sql */ File: ch13-14.sql */ DECLAREDECLARE v_FirstName employee.FirstName%TYPE;v_FirstName employee.FirstName%TYPE; v_LastName employee.LastName%TYPE;v_LastName employee.LastName%TYPE; search_ID employee.EmployeeID%TYPE;search_ID employee.EmployeeID%TYPE;BEGINBEGIN ManageEmployee.FindEmployee (&search_ID, v_FirstName, ManageEmployee.FindEmployee (&search_ID, v_FirstName, v_LastName);v_LastName); DBMS_OUTPUT.PUT_LINE ('The employee name is: ' || DBMS_OUTPUT.PUT_LINE ('The employee name is: ' || v_LastName || ', ' || v_FirstName);v_LastName || ', ' || v_FirstName);EXCEPTIONEXCEPTION WHEN OTHERS THENWHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE ('Cannot find an employee DBMS_OUTPUT.PUT_LINE ('Cannot find an employee

with that ID.');with that ID.');END;END;//

Page 40: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Results of Calling Package ProcedureResults of Calling Package Procedure

• When the employee identifier is valid, the code displays When the employee identifier is valid, the code displays the employee name as shown here. the employee name as shown here.

Enter value for search_id: '01885'Enter value for search_id: '01885'The employee name is: Bock, DouglasThe employee name is: Bock, DouglasPL/SQL procedure successfully completed.PL/SQL procedure successfully completed.

• When the identifier is not valid, the exception raised When the identifier is not valid, the exception raised within the called procedure is propagated back to the within the called procedure is propagated back to the calling procedure and is trapped by the EXCEPTION calling procedure and is trapped by the EXCEPTION section’s WHEN OTHERS clause and an appropriate section’s WHEN OTHERS clause and an appropriate message is displayed as shown here. message is displayed as shown here.

Enter value for search_id: '99999'Enter value for search_id: '99999'Cannot find an employee with that ID.Cannot find an employee with that ID.PL/SQL procedure successfully completed.PL/SQL procedure successfully completed.

Page 41: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Cursors in PackagesCursors in Packages • A A cursor variablecursor variable can make a cursor dynamic so that it is reusable and can make a cursor dynamic so that it is reusable and

sharable among different procedures and functions such as those sharable among different procedures and functions such as those created as part of a package. created as part of a package.

• A cursor variable has data type REF CURSOR. It is like a pointer in A cursor variable has data type REF CURSOR. It is like a pointer in the C language, and it points to a query work area where a result set is the C language, and it points to a query work area where a result set is stored. stored.

• First you must define a REF CURSOR type. First you must define a REF CURSOR type. • Next, you define a cursor variable of that type. In this general syntactic Next, you define a cursor variable of that type. In this general syntactic

example, the <return_type> object represents a row in a database table.example, the <return_type> object represents a row in a database table. TYPE ref_type_name IS REF CURSOR TYPE ref_type_name IS REF CURSOR [RETURN <return_type>];[RETURN <return_type>];

• This provides an example of declaring a cursor variable that can be used This provides an example of declaring a cursor variable that can be used to process data rows for the to process data rows for the equipmentequipment table of the Madison Hospital table of the Madison Hospital database.database.DECLAREDECLARE TYPE equipment_Type IS REF CURSOR TYPE equipment_Type IS REF CURSOR RETURN equipment%ROWTYPE;RETURN equipment%ROWTYPE; cv_Equipment IN OUT equipment_Type;cv_Equipment IN OUT equipment_Type;

Page 42: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.15 – REF CURSOR TypeExample 13.15 – REF CURSOR Type• The Package Specification declares a REF CURSOR type named The Package Specification declares a REF CURSOR type named

equipment_Typeequipment_Type and two procedures named two procedures named OpenItemOpenItem and and FetchItemFetchItem. . • The cursor cv_Equipment in the The cursor cv_Equipment in the OpenItemOpenItem procedure is declared as an IN procedure is declared as an IN

OUT parameter – it will store an equipment item after the procedure is OUT parameter – it will store an equipment item after the procedure is executed—it is this stored value that is input to the executed—it is this stored value that is input to the FetchItemFetchItem procedure. procedure.

/* /* PL SQL Example 13.15 PL SQL Example 13.15 File: ch13-15.sql */ File: ch13-15.sql */ CREATE OR REPLACE PACKAGE CREATE OR REPLACE PACKAGE ManageEquipmentManageEquipment AS AS -- Create REF CURSOR type-- Create REF CURSOR type TYPE equipment_Type IS REF CURSOR TYPE equipment_Type IS REF CURSOR RETURN equipment%ROWTYPE;RETURN equipment%ROWTYPE; -- Declare procedure -- Declare procedure PROCEDURE OpenItem (PROCEDURE OpenItem (cv_Equipment IN OUT equipment_Typecv_Equipment IN OUT equipment_Type, , p_EquipmentNumber IN CHAR); p_EquipmentNumber IN CHAR); -- Declare procedure to fetch an equipment item-- Declare procedure to fetch an equipment item PROCEDURE FetchItem (PROCEDURE FetchItem (cv_Equipment IN equipment_Typecv_Equipment IN equipment_Type, , equipment_Row OUT equipment%ROWTYPE);equipment_Row OUT equipment%ROWTYPE);END ManageEquipment;END ManageEquipment;

Page 43: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.16 – Package BodyExample 13.16 – Package Body/* PL SQL Example 13.16 File: ch13-16.sql *//* PL SQL Example 13.16 File: ch13-16.sql */CREATE OR REPLACE PACKAGE BODY ManageEquipment ASCREATE OR REPLACE PACKAGE BODY ManageEquipment AS -- Procedure to get a specific item of equipment-- Procedure to get a specific item of equipment PROCEDURE OpenItem (PROCEDURE OpenItem (cv_Equipment IN OUT equipment_Typecv_Equipment IN OUT equipment_Type, , p_EquipmentNumber IN CHAR) ASp_EquipmentNumber IN CHAR) AS BEGINBEGIN -- Populate the cursor -- Populate the cursor OPEN cv_Equipment FOR OPEN cv_Equipment FOR SELECT * FROM Equipment SELECT * FROM Equipment WHERE EquipmentNumber = p_EquipmentNumber;WHERE EquipmentNumber = p_EquipmentNumber; END OpenItem;END OpenItem; PROCEDURE FetchItem (PROCEDURE FetchItem (cv_Equipment IN equipment_Typecv_Equipment IN equipment_Type, , equipment_Row OUT equipment%ROWTYPE) ASequipment_Row OUT equipment%ROWTYPE) AS BEGINBEGIN FETCH cv_Equipment INTO equipment_Row;FETCH cv_Equipment INTO equipment_Row; END FetchItem;END FetchItem;END ManageEquipment;END ManageEquipment;

Page 44: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.16 – Use Cursor VariableExample 13.16 – Use Cursor Variable/* PL SQL Example 13.16 File: ch13-16.sql *//* PL SQL Example 13.16 File: ch13-16.sql */DECLAREDECLARE -- Declare a cursor variable of the REF CURSOR type-- Declare a cursor variable of the REF CURSOR type item_Cursor ManageEquipment.equipment_Type;item_Cursor ManageEquipment.equipment_Type; v_EquipmentNumber equipment.EquipmentNumber%TYPE;v_EquipmentNumber equipment.EquipmentNumber%TYPE; equipment_Row equipment%ROWTYPE;equipment_Row equipment%ROWTYPE;BEGINBEGIN -- Assign a equipment number to the variable-- Assign a equipment number to the variable v_EquipmentNumber := '5001';v_EquipmentNumber := '5001'; -- Open the cursor using a variable-- Open the cursor using a variable ManageEquipment.OpenItem (item_Cursor, v_EquipmentNumber);ManageEquipment.OpenItem (item_Cursor, v_EquipmentNumber); -- Fetch the equipment data and display it-- Fetch the equipment data and display it LOOPLOOP ManageEquipment.FetchItem( item_Cursor, equipment_Row);ManageEquipment.FetchItem( item_Cursor, equipment_Row); EXIT WHEN item_cursor%NOTFOUND;EXIT WHEN item_cursor%NOTFOUND; DBMS_OUTPUT.PUT (equipment_Row.EquipmentNumber || ' ');DBMS_OUTPUT.PUT (equipment_Row.EquipmentNumber || ' '); DBMS_OUTPUT.PUT_LINE (equipment_Row.Description);DBMS_OUTPUT.PUT_LINE (equipment_Row.Description); END LOOP;END LOOP; END;END;

5001 Computer, Desktop5001 Computer, DesktopPL/SQL procedure successfully completed.PL/SQL procedure successfully completed.

Page 45: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

DATABASE TRIGGERSDATABASE TRIGGERS• Database trigger – a stored PL/SQL program unit that is Database trigger – a stored PL/SQL program unit that is

associated with a specific database table, or with certain view associated with a specific database table, or with certain view types – can also be associated with a system event such as types – can also be associated with a system event such as database startup.database startup.

• Triggers execute (fire) automatically for specified SQL DML Triggers execute (fire) automatically for specified SQL DML operations – INSERT, UPDATE, or DELETE affecting one or operations – INSERT, UPDATE, or DELETE affecting one or more rows of a table. more rows of a table.

• Database triggers can be used to perform any of the following Database triggers can be used to perform any of the following tasks:tasks:– Audit data modification.Audit data modification.– Log events transparently.Log events transparently.– Enforce complex business rules.Enforce complex business rules.– Derive column values automatically. Derive column values automatically. – Implement complex security authorizations. Implement complex security authorizations. – Maintain replicate tables.Maintain replicate tables.– Publish information about events for a publish-subscribe environment such Publish information about events for a publish-subscribe environment such

as that associated with web programming.as that associated with web programming.

Page 46: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Facts About TriggersFacts About Triggers• Triggers:Triggers:

– are named PL/SQL blocks with declarative, are named PL/SQL blocks with declarative, executable, and exception handling sections. executable, and exception handling sections.

– are stand-alone database objects – they are not are stand-alone database objects – they are not stored as part of a package and cannot be local to a stored as part of a package and cannot be local to a block. block.

– do not accept arguments. do not accept arguments. • To create/test a trigger, you (not the system user To create/test a trigger, you (not the system user

of the trigger) must have appropriate access to all of the trigger) must have appropriate access to all objects referenced by a trigger action. objects referenced by a trigger action.

• Example: To create a BEFORE INSERT trigger Example: To create a BEFORE INSERT trigger for the for the employeeemployee table requires you to have table requires you to have INSERT ROW privileges for the table.INSERT ROW privileges for the table.

Page 47: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Trigger LimitationsTrigger Limitations

• Triggers Triggers cannot contain cannot contain the COMMIT, the COMMIT, ROLLBACK, and SAVEPOINT ROLLBACK, and SAVEPOINT statements. statements.

• Trigger body – cannot exceed 32K in size. Trigger body – cannot exceed 32K in size. • No limit on the number of triggers defined No limit on the number of triggers defined

for a DML statement for a table. In fact, you for a DML statement for a table. In fact, you can define two triggers of the same type for a can define two triggers of the same type for a table. When this occurs, the triggers of the table. When this occurs, the triggers of the same type fire sequentially.same type fire sequentially.

Page 48: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Create Trigger SyntaxCreate Trigger SyntaxCREATE [OR REPLACE] TRIGGER trigger_nameCREATE [OR REPLACE] TRIGGER trigger_name{BEFORE|AFTER|INSTEAD OF} triggering_event {BEFORE|AFTER|INSTEAD OF} triggering_event

[referencing_clause] ON {table_name | view_name}[referencing_clause] ON {table_name | view_name}[WHEN condition] [FOR EACH ROW] [WHEN condition] [FOR EACH ROW] DECLAREDECLARE Declaration statementsDeclaration statements[BEGIN[BEGIN Executable statementsExecutable statementsEXCEPTIONEXCEPTION Exception-handling statements]Exception-handling statements]END;END;

• The trigger body must have at least the executable section. The trigger body must have at least the executable section. • The declarative and exception handling sections are optional. The declarative and exception handling sections are optional.

• When there is a declarative section, the trigger body must When there is a declarative section, the trigger body must

start with the DECLARE keyword. start with the DECLARE keyword. • The WHEN clause specifies the condition under which a The WHEN clause specifies the condition under which a

trigger should fire.trigger should fire.

Page 49: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Trigger TypesTrigger Types• BEFORE and AFTER Triggers – trigger fires before or after BEFORE and AFTER Triggers – trigger fires before or after

the triggering event. Applies only to tables.the triggering event. Applies only to tables.• INSTEAD OF Trigger – trigger fires instead of the triggering INSTEAD OF Trigger – trigger fires instead of the triggering

event. Applies only to views.event. Applies only to views.• Triggering_event – a DML statement issued against the table Triggering_event – a DML statement issued against the table

or view named in the ON clause – example: INSERT, or view named in the ON clause – example: INSERT, UPDATE, or DELETE.UPDATE, or DELETE.

• DML triggers are fired by DML statements and are referred to DML triggers are fired by DML statements and are referred to sometimes as row triggers. sometimes as row triggers.

• FOR EACH ROW clause – a ROW trigger that fires once for FOR EACH ROW clause – a ROW trigger that fires once for each modified row. each modified row.

• STATEMENT trigger – fires once for the DML statement.STATEMENT trigger – fires once for the DML statement.• Referencing_clause – enables writing code to refer to the data Referencing_clause – enables writing code to refer to the data

in the row currently being modified by a different name. in the row currently being modified by a different name.

Page 50: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.17 – STATEMENT TriggerExample 13.17 – STATEMENT Trigger

/* PL SQL Example 13.17 File: ch13-17.sql *//* PL SQL Example 13.17 File: ch13-17.sql */CREATE OR REPLACE TRIGGER SecureEmployee CREATE OR REPLACE TRIGGER SecureEmployee BEFORE DELETE OR INSERT OR UPDATE ON employeeBEFORE DELETE OR INSERT OR UPDATE ON employeeBEGINBEGIN IF (TO_CHAR(SYSDATE, 'day') IN ('saturday', 'sunday')) IF (TO_CHAR(SYSDATE, 'day') IN ('saturday', 'sunday'))

OROR (TO_CHAR(SYSDATE, 'hh24:mi') NOT (TO_CHAR(SYSDATE, 'hh24:mi') NOT BETWEEN '08:30' AND '18:30') THENBETWEEN '08:30' AND '18:30') THEN RAISE_APPLICATION_ERROR(-20500, RAISE_APPLICATION_ERROR(-20500, 'Employee table is secured');'Employee table is secured'); END IF;END IF;END;END;//

• Trigger uses the RAISE_APPLICATION_ERROR statement to Trigger uses the RAISE_APPLICATION_ERROR statement to inform the application user that the table is secure and cannot inform the application user that the table is secure and cannot be modified on a weekend day (Saturday or Sunday) or prior to be modified on a weekend day (Saturday or Sunday) or prior to 8:30 a.m. or after 6:30 p.m. 8:30 a.m. or after 6:30 p.m.

Page 51: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Testing the Testing the SecureEmployeeSecureEmployee Trigger Trigger

SQL> UPDATE Employee SET Salary = 10 SQL> UPDATE Employee SET Salary = 10

WHERE EmployeeID = '01885';WHERE EmployeeID = '01885';

UPDATE Employee SET Salary = 10 WHERE EmployeeID UPDATE Employee SET Salary = 10 WHERE EmployeeID = '01885'= '01885'

**

ERROR at line 1:ERROR at line 1:

ORA-20500: table is securedORA-20500: table is secured

ORA-06512: at "ORA-06512: at "DBOCK.SECUREEMPLOYEEDBOCK.SECUREEMPLOYEE", line 4", line 4

ORA-04088: error during execution of trigger ORA-04088: error during execution of trigger 'DBOCK.SECUREEMPLOYEE''DBOCK.SECUREEMPLOYEE'

Page 52: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

ROW Trigger – Accessing RowsROW Trigger – Accessing Rows• Access data on the row currently being processed Access data on the row currently being processed

by using two correlation identifiers named :old by using two correlation identifiers named :old and :new. These are special Oracle bind and :new. These are special Oracle bind variables. variables.

• The PL/SQL compiler treats the :old and :new The PL/SQL compiler treats the :old and :new records as records of type records as records of type trigger_Table_Nametrigger_Table_Name%ROWTYPE%ROWTYPE. .

• To reference a column in the triggering table, use To reference a column in the triggering table, use the notation shown here where the the notation shown here where the ColumnNameColumnName value is a valid column in the triggering table. value is a valid column in the triggering table.

:new.ColumnName:new.ColumnName:old.ColumnName:old.ColumnName

Page 53: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Bind Variables :old and :new DefinedBind Variables :old and :new Defined

DML StatementDML Statement :old:old :new:new

INSERTINSERT Undefined – all column Undefined – all column values are NULL as values are NULL as there is no “old” version there is no “old” version of the data row being of the data row being inserted.inserted.

Stores the values that Stores the values that will be inserted into the will be inserted into the new row for the table.new row for the table.

UPDATEUPDATE Stores the original values Stores the original values for the row being for the row being updated before the updated before the update takes place.update takes place.

Stores the new values for Stores the new values for the row – values the row the row – values the row will contain after the will contain after the update takes place.update takes place.

DELETEDELETE Stores the original values Stores the original values for the row being deleted for the row being deleted before the deletion takes before the deletion takes place.place.

Undefined – all column Undefined – all column values are NULL as values are NULL as there will not be a “new” there will not be a “new” version of the row being version of the row being deleted.deleted.

Page 54: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Audit Log Application – Audit Log Application – EquipmentEquipment Table Table ExampleExample

• Triggers can automate the creation of an audit log when a Triggers can automate the creation of an audit log when a table is modified.table is modified.

• Create an Create an Equipment_AuditEquipment_Audit table to store audit log records. table to store audit log records.

/* PL SQL Example 13.18 File: ch13-18.sql *//* PL SQL Example 13.18 File: ch13-18.sql */

CREATE TABLE Equipment_Audit (CREATE TABLE Equipment_Audit (

Action VARCHAR2(10),Action VARCHAR2(10),

ActionDate DATE DEFAULT SYSDATE,ActionDate DATE DEFAULT SYSDATE,

EquipmentNumber CHAR(4),EquipmentNumber CHAR(4),

Description VARCHAR2(25),Description VARCHAR2(25),

OriginalCost NUMBER(7,2),OriginalCost NUMBER(7,2),

QuantityAvailable NUMBER(4),QuantityAvailable NUMBER(4),

ProjectNumber NUMBER(4));ProjectNumber NUMBER(4));

Page 55: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.19 – Example 13.19 – AuditEquipmentAuditEquipment Trigger Trigger/* PL SQL Example 13.19 File: ch13-19.sql *//* PL SQL Example 13.19 File: ch13-19.sql */CREATE OR REPLACE TRIGGER AuditEquipment CREATE OR REPLACE TRIGGER AuditEquipment AFTER DELETE OR INSERT OR UPDATE ON Equipment AFTER DELETE OR INSERT OR UPDATE ON Equipment FOR EACH ROWFOR EACH ROWBEGIN BEGIN IF DELETING THEN IF DELETING THEN INSERT INTO equipment_audit VALUES ('DELETE', SYSDATE,INSERT INTO equipment_audit VALUES ('DELETE', SYSDATE, :old.EquipmentNumber, :old.Description, :old.OriginalCost,:old.EquipmentNumber, :old.Description, :old.OriginalCost, :old.QuantityAvailable, :old.ProjectNumber);:old.QuantityAvailable, :old.ProjectNumber); ELSIF INSERTING THENELSIF INSERTING THEN INSERT INTO equipment_audit VALUES ('INSERT', SYSDATE, INSERT INTO equipment_audit VALUES ('INSERT', SYSDATE, :new.EquipmentNumber, :new.Description, :new.OriginalCost,:new.EquipmentNumber, :new.Description, :new.OriginalCost, :new.QuantityAvailable, :new.ProjectNumber);:new.QuantityAvailable, :new.ProjectNumber); ELSE -- updating - Insert a before and after image of updatesELSE -- updating - Insert a before and after image of updates INSERT INTO equipment_audit VALUES ('UPDATE-OLD', SYSDATE,INSERT INTO equipment_audit VALUES ('UPDATE-OLD', SYSDATE, :old.EquipmentNumber, :old.Description, :old.OriginalCost, :old.EquipmentNumber, :old.Description, :old.OriginalCost, :old.QuantityAvailable, :old.ProjectNumber);:old.QuantityAvailable, :old.ProjectNumber); INSERT INTO equipment_audit VALUES ('UPDATE-NEW', SYSDATE, INSERT INTO equipment_audit VALUES ('UPDATE-NEW', SYSDATE, :new.EquipmentNumber, :new.Description, :new.OriginalCost, :new.EquipmentNumber, :new.Description, :new.OriginalCost, :new.QuantityAvailable, :new.ProjectNumber);:new.QuantityAvailable, :new.ProjectNumber); END IF;END IF;END;END;

Page 56: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Trigger PredicatesTrigger Predicates• There are three trigger predicates that can be used to There are three trigger predicates that can be used to

determine if a trigger is responding to a specific determine if a trigger is responding to a specific DML statement: DML statement: INSERTINGINSERTING, , UPDATINGUPDATING, and , and DELETINGDELETING. .

• PL/SQL Example 13.19 uses two of these in the IF-PL/SQL Example 13.19 uses two of these in the IF-ELSIF-ELSE structure. ELSIF-ELSE structure.

• These predicates return TRUE if the triggering These predicates return TRUE if the triggering statement is of the type specified; otherwise, they statement is of the type specified; otherwise, they return FALSE.return FALSE.

• PL/SQL Example 13.20 tests the PL/SQL Example 13.20 tests the AuditEquipmentAuditEquipment trigger by inserting a new row, modifying the new trigger by inserting a new row, modifying the new row, and deleting the new row (next slide).row, and deleting the new row (next slide).

Page 57: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Example 13.20 – Test Example 13.20 – Test EquipmentAuditEquipmentAudit Trigger Trigger

/* PL SQL Example 13.20 File: ch13-20.sql *//* PL SQL Example 13.20 File: ch13-20.sql */-- Insert new equipment row-- Insert new equipment rowINSERT INTO Equipment VALUES('9000', 'X-Ray Table', 15500.00, 1, 8);INSERT INTO Equipment VALUES('9000', 'X-Ray Table', 15500.00, 1, 8);COMMIT;COMMIT;-- Modify equipment row-- Modify equipment rowUPDATE Equipment SET QuantityAvailable = 2 UPDATE Equipment SET QuantityAvailable = 2 WHERE EquipmentNumber = '9000';WHERE EquipmentNumber = '9000';COMMIT;COMMIT;-- Delete equipment row-- Delete equipment rowDELETE FROM Equipment WHERE EquipmentNumber = '9000';DELETE FROM Equipment WHERE EquipmentNumber = '9000';COMMIT;COMMIT;

-- List rows in Equipment_Audit table.-- List rows in Equipment_Audit table.SELECT * FROM Equipment_Audit;SELECT * FROM Equipment_Audit;ACTION ACTIONDAT EQUI DESCRIPTION ORIGINALCOST QUAN PROJACTION ACTIONDAT EQUI DESCRIPTION ORIGINALCOST QUAN PROJ---------- --------- ---- ------------ ------------ ---- -------------- --------- ---- ------------ ------------ ---- ----INSERT 25-NOV-07 9000 X-Ray Table 15500 1 8INSERT 25-NOV-07 9000 X-Ray Table 15500 1 8UPDATE-OLD 25-NOV-07 9000 X-Ray Table 15500 1 8UPDATE-OLD 25-NOV-07 9000 X-Ray Table 15500 1 8UPDATE-NEW 25-NOV-07 9000 X-Ray Table 15500 2 8UPDATE-NEW 25-NOV-07 9000 X-Ray Table 15500 2 8DELETE 25-NOV-07 9000 X-Ray Table 15500 2 8DELETE 25-NOV-07 9000 X-Ray Table 15500 2 8

Page 58: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

WHEN ClauseWHEN Clause• The WHEN clause only applies to ROW triggers. The WHEN clause only applies to ROW triggers. • The body of the trigger executes only when the condition The body of the trigger executes only when the condition

specified is met. specified is met. • PL/SQL Example 13.21 provides a partial outline for the logic PL/SQL Example 13.21 provides a partial outline for the logic

of a trigger that includes a WHEN clause for high value items. of a trigger that includes a WHEN clause for high value items. • Note the seemingly inconsistent use of the :new bind variable in Note the seemingly inconsistent use of the :new bind variable in

the WHEN clause – this syntax is correct – you do not specify the WHEN clause – this syntax is correct – you do not specify the colon as part of the reference to the pseudo column.the colon as part of the reference to the pseudo column./* PL SQL Example 13.21 *//* PL SQL Example 13.21 */CREATE OR REPLACE TRIGGER HighCostCREATE OR REPLACE TRIGGER HighCost BEFORE INSERT OR UPDATE OF OriginalCost BEFORE INSERT OR UPDATE OF OriginalCost ON equipmentON equipmentFOR EACH ROWFOR EACH ROWWHEN (new.OriginalCost > 15000) BEGINWHEN (new.OriginalCost > 15000) BEGIN /* Trigger body action is coded here *//* Trigger body action is coded here */ NULL;NULL;END;END;

Page 59: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Enabling and Disabling TriggersEnabling and Disabling Triggers • It is useful to be able to enable and disable triggers; example, a It is useful to be able to enable and disable triggers; example, a

script will bulk load the script will bulk load the equipmentequipment table – firing a trigger table – firing a trigger during a bulk load for every row can degrade performance of during a bulk load for every row can degrade performance of the load.the load.

• By default, triggers are enabled. By default, triggers are enabled. • A disabled trigger does not execute the trigger body even if the A disabled trigger does not execute the trigger body even if the

triggering statement is issued. The syntax for enabling and triggering statement is issued. The syntax for enabling and disabling triggers is:disabling triggers is:-- Disable an individual trigger by name.-- Disable an individual trigger by name.ALTER TRIGGER trigger_name DISABLE;ALTER TRIGGER trigger_name DISABLE;-- Disable all triggers associated with a table.-- Disable all triggers associated with a table.ALTER TABLE table_name DISABLE ALL TRIGGERS;ALTER TABLE table_name DISABLE ALL TRIGGERS;-- Enable a trigger that was disabled.-- Enable a trigger that was disabled.ALTER TRIGGER trigger_name ENABLE;ALTER TRIGGER trigger_name ENABLE;-- Enable all triggers associated with a table.-- Enable all triggers associated with a table.

ALTER TABLE table_name ENABLE ALL TRIGGERS;ALTER TABLE table_name ENABLE ALL TRIGGERS;

Page 60: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

Dropping a TriggerDropping a Trigger

• The DROP TRIGGER statement drops a The DROP TRIGGER statement drops a trigger from the database. trigger from the database.

• If you drop a table, all associated table If you drop a table, all associated table triggers are also dropped. triggers are also dropped.

• The syntax is: The syntax is: DROP TRIGGER trigger_name;DROP TRIGGER trigger_name;

Page 61: Chapter 13 : PROCEDURES, FUNCTIONS, PACKAGES, and TRIGGERS

Bordoloi and BockBordoloi and Bock

SummarySummary• Created/replaced named procedures and functions.• Created packages that group PL/SQL types, variables,

exceptions, and subprograms that are logically related. • Write PL/SQL blocks that called packages, procedures, and

functions.• Write exception-handling code for the above objects.• Used different parameter types to pass values to/from a

procedure and function.• Created triggers to manage complex business rules, establish

special audit trails, and derive column values automatically. • Created both STATEMENT and ROW triggers and used

triggers for a common database processing task, creating an audit trail to track changes made to the data stored in a table.