Introduction to Oracle 11g PL/SQL · PDF fileIntroduction to Oracle 11g PL/SQL Programming...
Transcript of Introduction to Oracle 11g PL/SQL · PDF fileIntroduction to Oracle 11g PL/SQL Programming...
Introduction to
Oracle 11g PL/SQL
Programming
Student Workbook
Page ii Rev 05-14-09 © 2009 ITCourseware, LLC
Introduction to Oracle 11g PL/SQL Programming
Introduction to Oracle 11g PL/SQL Programming
Contributing Authors: Danielle Hopkins, Julie Johnson, Rob Roselius, and Robert Seitz
Published by ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, CO 80112.
Copyeditor: Danielle North
Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of this
workbook, including Roger Jones, Jim McNally, and Kevin Smith, and the many students who have offered
comments, suggestions, criticisms, and insights.
Copyright © 2009 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced or
utilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or by an
information storage retrieval system, without permission in writing from the publisher. Inquiries should be
addressed to ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112.
(303) 302-5280.
All brand names, product names, trademarks, and registered trademarks are the property of their respective
owners.
© 2009 ITCourseware, LLC Rev 05-14-09 Page iii
Introduction to Oracle 11g PL/SQL Programming
Contents
Chapter 1 - Course Introduction ............................................................................................................. 9
Course Objectives .......................................................................................................................... 10
Course Overview ........................................................................................................................... 12
Using the Workbook ...................................................................................................................... 13
Suggested References ..................................................................................................................... 14
Sample Database ............................................................................................................................ 16
Chapter 2 - Triggers ............................................................................................................................. 21
Beyond Declarative Integrity ........................................................................................................... 22
Triggers .......................................................................................................................................... 24
Types of Triggers ............................................................................................................................ 26
Trigger Sequencing ......................................................................................................................... 28
Row-Level Triggers ........................................................................................................................ 30
Trigger Predicates ........................................................................................................................... 32
Trigger Conditions .......................................................................................................................... 34
Using SEQUENCEs ....................................................................................................................... 36
Cascading Triggers and Mutating Tables .......................................................................................... 38
Generating an Error ........................................................................................................................ 40
Maintaining Triggers ........................................................................................................................ 42
Labs ............................................................................................................................................... 44
Chapter 3 - PL/SQL Variables and Datatypes ....................................................................................... 47
Anonymous Blocks ......................................................................................................................... 48
Declaring Variables ......................................................................................................................... 50
Datatypes ....................................................................................................................................... 52
Subtypes ........................................................................................................................................ 54
Character Data ............................................................................................................................... 56
Dates and Timestamps .................................................................................................................... 58
Date Intervals ................................................................................................................................. 60
Anchored Types ............................................................................................................................. 62
Assignment and Conversions ........................................................................................................... 64
Selecting into a Variable .................................................................................................................. 66
Returning into a Variable ................................................................................................................. 68
Labs ............................................................................................................................................... 70
Page iv Rev 05-14-09 © 2009 ITCourseware, LLC
Introduction to Oracle 11g PL/SQL Programming
Chapter 4 - PL/SQL Syntax and Logic ................................................................................................. 73
Conditional Statements — IF/THEN............................................................................................... 74
Conditional Statements — CASE ................................................................................................... 76
Comments and Labels .................................................................................................................... 78
Loops ............................................................................................................................................ 80
WHILE and FOR Loops ................................................................................................................ 82
SQL in PL/SQL ............................................................................................................................. 84
Local Procedures and Functions ..................................................................................................... 86
Labs ............................................................................................................................................... 88
Chapter 5 - Stored Procedures and Functions ....................................................................................... 91
Stored Subprograms ....................................................................................................................... 92
Creating a Stored Procedure ........................................................................................................... 94
Procedure Calls and Parameters ..................................................................................................... 96
Parameter Modes ........................................................................................................................... 98
Named Parameter Notation .......................................................................................................... 100
Default Arguments ........................................................................................................................ 102
Creating a Stored Function ........................................................................................................... 104
Stored Functions and SQL ........................................................................................................... 106
Invoker's Rights ............................................................................................................................ 108
Labs ............................................................................................................................................. 110
Chapter 6 - Exception Handling .......................................................................................................... 113
SQLCODE and SQLERRM ........................................................................................................ 114
Exception Handlers ....................................................................................................................... 116
Nesting Blocks ............................................................................................................................. 118
Scope and Name Resolution ......................................................................................................... 120
Declaring and Raising Named Exceptions ...................................................................................... 122
User-Defined Exceptions .............................................................................................................. 124
Labs ............................................................................................................................................. 126
Chapter 7 - Records, Collections, and User-Defined Types ................................................................. 129
Record Variables .......................................................................................................................... 130
Using the %ROWTYPE Attribute ................................................................................................. 132
User-Defined Object Types .......................................................................................................... 134
VARRAY and Nested TABLE Collections .................................................................................... 136
Using Nested TABLEs ................................................................................................................. 138
Using VARRAYs .......................................................................................................................... 140
© 2009 ITCourseware, LLC Rev 05-14-09 Page v
Introduction to Oracle 11g PL/SQL Programming
Collections in Database Tables ...................................................................................................... 142
Associative Array Collections ........................................................................................................ 144
Collection Methods ...................................................................................................................... 146
Iterating Through Collections ......................................................................................................... 148
Labs ............................................................................................................................................. 150
Chapter 8 - Cursors ........................................................................................................................... 153
Multi-Row Queries ....................................................................................................................... 154
Declaring and Opening Cursors ..................................................................................................... 156
Fetching Rows .............................................................................................................................. 158
Closing Cursors ............................................................................................................................ 160
The Cursor FOR Loop ................................................................................................................. 162
FOR UPDATE Cursors ................................................................................................................ 164
Cursor Parameters ........................................................................................................................ 166
The Implicit (SQL) Cursor ............................................................................................................ 168
Labs ............................................................................................................................................. 170
Chapter 9 - Bulk Operations ............................................................................................................... 173
Bulk Binding ................................................................................................................................. 174
BULK COLLECT Clause ............................................................................................................ 176
FORALL Statement ..................................................................................................................... 178
FORALL Variations ...................................................................................................................... 180
Bulk Returns ................................................................................................................................. 182
Bulk Fetching with Cursors ........................................................................................................... 184
Labs ............................................................................................................................................. 186
Chapter 10 - Using Packages ............................................................................................................. 189
Packages ...................................................................................................................................... 190
Oracle-Supplied Packages ............................................................................................................ 192
The DBMS_OUTPUT Package ................................................................................................... 194
The DBMS_UTILITY Package .................................................................................................... 196
The UTL_FILE Package .............................................................................................................. 198
Creating Pipes with DBMS_PIPE ................................................................................................. 200
Writing to and Reading from a Pipe ............................................................................................... 202
The DBMS_METADATA Package .............................................................................................. 204
XML Packages ............................................................................................................................ 206
Networking Packages ................................................................................................................... 208
Other Supplied Packages .............................................................................................................. 210
Labs ............................................................................................................................................. 212
Page vi Rev 05-14-09 © 2009 ITCourseware, LLC
Introduction to Oracle 11g PL/SQL Programming
Chapter 11 - Creating Packages ......................................................................................................... 215
Structure of a Package .................................................................................................................. 216
The Package Interface and Implementation .................................................................................... 218
Package Variables and Package State ........................................................................................... 220
Overloading Package Functions and Procedures ........................................................................... 222
Forward Declarations ................................................................................................................... 224
Strong REF CURSOR Variables ................................................................................................... 226
Weak REF CURSOR Variables .................................................................................................... 228
Labs ............................................................................................................................................. 230
Chapter 12 - Working with LOBs ....................................................................................................... 233
Large Object Types ...................................................................................................................... 234
Oracle Directories ........................................................................................................................ 236
LOB Locators .............................................................................................................................. 238
Internal LOBs ............................................................................................................................... 240
LOB Storage and SECUREFILEs ................................................................................................ 242
External LOBs .............................................................................................................................. 244
Temporary LOBs ......................................................................................................................... 246
The DBMS_LOB Package ........................................................................................................... 248
Labs ............................................................................................................................................. 250
Chapter 13 - Maintaining PL/SQL Code ............................................................................................. 253
Privileges for Stored Programs ...................................................................................................... 254
Data Dictionary ............................................................................................................................ 256
PL/SQL Stored Program Compilation ........................................................................................... 258
Conditional Compilation ................................................................................................................ 260
Compile-Time Warnings ................................................................................................................ 262
The PL/SQL Execution Environment ............................................................................................. 264
Dependencies and Validation ......................................................................................................... 266
Maintaining Stored Programs ........................................................................................................ 268
Labs ............................................................................................................................................. 270
Appendix A - Dynamic SQL ............................................................................................................... 273
Generating SQL at Runtime ........................................................................................................... 274
Native Dynamic SQL vs. DBMS_SQL Package ........................................................................... 276
The EXECUTE IMMEDIATE Statement ...................................................................................... 278
Using Bind Variables ..................................................................................................................... 280
Multi-row Dynamic Queries .......................................................................................................... 282
© 2009 ITCourseware, LLC Rev 05-14-09 Page vii
Introduction to Oracle 11g PL/SQL Programming
Bulk Operations with Dynamic SQL ............................................................................................. 284
Using DBMS_SQL ...................................................................................................................... 286
DBMS_SQL Subprograms ........................................................................................................... 288
Appendix B - PL/SQL Versions, Datatypes and Language Limits ......................................................... 291
Appendix C - Oracle 11g Supplied Packages ...................................................................................... 299
Solutions ............................................................................................................................................ 311
Index .................................................................................................................................................. 343
Page viii Rev 05-14-09 © 2009 ITCourseware, LLC
Introduction to Oracle 11g PL/SQL Programming
Course IntroductionChapter 1
© 2009 ITCourseware, LLC Rev 05-14-09 Page 9
Chapter 1 - Course Introduction
Introduction to Oracle 11g PL/SQL Programming
Page 10 Rev 05-14-09 © 2009 ITCourseware, LLC
� Create triggers on database tables.
� Use PL/SQL's datatypes for database and program data.
� Use program stucture and control flow to design and write PL/SQL programs.
� Create PL/SQL stored procedures and functions.
� Write robust programs that handle runtime exceptions.
� Use PL/SQL's collection datatypes.
� Use cursors to work with database data.
� Use the packages supplied with Oracle.
� Design and write your own packages.
� Maintain and evolve your PL/SQL programs.
� Manage the security of your stored PL/SQL programs.
Course Objectives
Course IntroductionChapter 1
© 2009 ITCourseware, LLC Rev 05-14-09 Page 11
Introduction to Oracle 11g PL/SQL Programming
Page 12 Rev 05-14-09 © 2009 ITCourseware, LLC
� Audience: This course is designed for database application developers
programming in an Oracle environment.
� Prerequisites: A working knowledge of the SQL language, as well as a solid
understanding of 3GL programming is required.
� Classroom Environment:
� One workstation per student.
� Oracle Server and SQL*Plus.
Course Overview
Course IntroductionChapter 1
© 2009 ITCourseware, LLC Rev 05-14-09 Page 13
Using the Workbook
Chapter 2 Servlet Basics
© 2002 ITCourseware, LLC Rev 2.0.0 Page 17
Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date
along with the current date:
Today.java
...
public class Today extends GenericServlet {
private Date bornOn;
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException
{
...
// Write the document
out.println("This servlet was born on " + bornOn.toString());
out.println("It is now " + today.toString());
}
public void init() {
bornOn = new Date();
}
}
Hands On:
The init() method is
called when the servlet is
loaded into the container.
This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When you
lay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topic
page contains the points to be discussed in class. The Support page has code examples, diagrams, screen
shots and additional information. Hands On sections provide opportunities for practical application of key
concepts. Try It and Investigate sections help direct individual discovery.
In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well as
on-line if you need a little help.
Java Servlets
Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC
� The servlet container controls the life cycle of the servlet.
� When the first request is received, the container loads the servlet class
and calls the init() method.
� For every request, the container uses a separate thread to call
the service() method.
� When the servlet is unloaded, the container calls the destroy()
method.
� As with Java’s finalize() method, don’t count on this being
called.
� Override one of the init() methods for one-time initializations, instead of
using a constructor.
� The simplest form takes no parameters.
public void init() {...}
� If you need to know container-specific configuration information, use
the other version.
public void init(ServletConfig config) {...
� Whenever you use the ServletConfig approach, always call the
superclass method, which performs additional initializations.
super.init(config);
The Servlet Life Cycle
The Topic page provides
the main topics for
classroom discussion.
The Support page has
additional information,
examples and suggestions.
Code examples are in afixed font and shaded. The
on-line file name is listed
above the shaded area.
Screen shots show
examples of what you
should see in class.
Topics are organized into
first (�), second (�) and
third (�) level points.
Pages are numbered
sequentially throughout
the book, making lookup
easy.
Callout boxes point out
important parts of the
example code.
Introduction to Oracle 11g PL/SQL Programming
Page 14 Rev 05-14-09 © 2009 ITCourseware, LLC
Allen, Christopher. 2004. Oracle Database 10g PL/SQL 101. McGraw-Hill Osborne, Emeryville, CA.
ISBN 0072255404
Boardman, Susan, Melanie Caffrey, Solomon Morse, and Benjamin Rosenzweig. 2002. Oracle Web
Application Programming for PL/SQL Developers. Prentice Hall PTR, Upper Saddle River,
NJ. ISBN 0130477311
Date, C.J and Hugh Darwen. 1996. A Guide to SQL Standard. Addison-Wesley, Boston, MA.
ISBN 0201964260
Date, C.J. 2003. An Introduction to Database Systems. Addison-Wesley, Boston, MA.
ISBN 0321197844
Feuerstein, Steven, Charles Dye, and John Beresniewicz. 1998. Oracle Built-in Packages. O'Reilly and
Associates, Sebastopol, CA. ISBN 1565923758
Feuerstein, Steven. 2007. Oracle PL/SQL Best Practices, Second Edition. O'Reilly and Associates,
Sebastopol, CA. ISBN 0596514107
Feuerstein, Steven. 2000. Oracle PL/SQL Developer's Workbook. O'Reilly and Associates, Sebastopol,
CA. ISBN 1565926749
Feuerstein, Steven and Bill Pribyl. 2005. Oracle PL/SQL Programming, Fourth Edition. O'Reilly and
Associates, Sebastopol, CA. ISBN 0596009771
Loney, Kevin. 2004. Oracle Database 10g: The Complete Reference. McGraw-Hill Osborne,
Emeryville, CA. ISBN 0072253517
McDonald, Connor, Chaim Katz, Christopher Beck, Joel R. Kallman, and David C. Knox. 2004.
Mastering Oracle PL/SQL: Practical Solutions. Apress, Berkeley, CA.
ISBN 1590592174
McLaughlin, Michael. 2008. Oracle Database 11g PL/SQL Programming. McGraw-Hill Osborne,
Emeryville, CA. ISBN 0071494456
Pribyl, Bill. 2001. Learning Oracle PL/SQL. O'Reilly and Associates, Sebastopol, CA.
ISBN 0596001800
Price, Jason. 2004. Oracle Database 10g SQL. McGraw-Hill Osborne, Emeryville, CA.
ISBN 0072229810
Suggested References
Course IntroductionChapter 1
© 2009 ITCourseware, LLC Rev 05-14-09 Page 15
Rosenzweig, Benjamin and Elena Silvestrova Rakhimov. 2008. Oracle PL/SQL by Example. Prentice Hall
PTR, Upper Saddle River, NJ. ISBN 0137144229
Urman, Scott and Michael McLaughlin. 2004. Oracle Database 10g PL/SQL Programming. McGraw-
Hill Osborne, Emeryville, CA. ISBN 0072230665
asktom.oracle.com
www.oracle.com/technology/tech/pl_sql
tahiti.oracle.com
Introduction to Oracle 11g PL/SQL Programming
Page 16 Rev 05-14-09 © 2009 ITCourseware, LLC
Sample Database
Our company is a hardware/software retailer with stores in several cities.
We keep track of each person's name, address, and phone. In addition, if a person is
an employee, we must record in which store he or she works, the supervisor's ID, the
employees's title, pay amount, and compensation type ("Hourly," "Salaried," etc.)
Sometimes a customer will fill out an order, which requires an invoice number. Each
invoice lists the store and the customer's ID. We record the quantity of each item on
the invoice and any discount for that item. We also keep track of how much the
customer has paid on the order.
When a credit account is used for an order, the balance for the account must be
updated to reflect the total amount of the invoice (including tax). The salesperson
verifies (with a phone call) that the person is a valid user of the account.
Each product we sell has a product ID and description. In addition, we keep track of
the vendor we purchase that product from, the ID for that product, and the category
("Software," "Peripheral," or "Service"). We also store the address, phone, and sales
rep ID for each individual vendor.
We keep track of how many items are on hand at each store and how many each store
has on order. When an item is sold, the inventory is updated.
We maintain the address, phone number, and manager ID for each store. Each store
has a unique store number. We record the sales tax rate for that store.
When a store runs low on a product, we create a purchase order. Each purchase
order in our company has a unique PO number. A PO is sent to a single vendor, from
which we might be ordering several items, each at a specific unit cost. The inventory
reflects the sale or order of any item in a store.
Course IntroductionChapter 1
© 2009 ITCourseware, LLC Rev 05-14-09 Page 17
ACCOUNT_TYPE_CODE = ACCOUNT_TYPE_CODE
ID = CUSTOMER_ID
ID = SUPERVISOR_ID
PAY_TYPE_CODE = PAY_TYPE_CODE
ID = ID
PRODUCT_ID = PRODUCT_ID
STORE_NUM BER = STORE_NUM BER
ACCOUNT_NUMBER = ACCOUNT_NUM BER
ID = CUSTOM ER_ID
STORE_NUM BER = STORE_NUM BER
INVOICE_NUMBER = INVOICE_NUMBER
PRODUCT_ID = PRODUCT_ID
STORE_NUM BER = STORE_NUM BER
VENDOR_ID = VENDOR_ID
PO_NUM BER = PO_NUMBERPRODUCT_ID = PRODUCT_ID
PRODUCT_CATEGORY_CODE = PRODUCT_CATEGORY_CODE
VENDOR_ID = VENDOR_ID
ID = VENDOR_REP_ID
ACCOUNT
ACCOUNT_NUMBER
ACCOUNT_NAME
ACCOUNT_TYPE_CODE
CUSTOMER_ID
CREDIT_LIM IT
BALANCE
STREET
CITY
STATE
NUMBER
VARCHAR2(25)
CHAR(1)
NUMBER
NUMBER(9,2)
NUMBER(9,2)
VARCHAR2(45)
VARCHAR2(25)
CHAR(2)
ACCOUNT_TYPE
ACCOUNT_TYPE_CODE
ACCOUNT_TYPE_NAME
INITIAL_DISCOUNT
CHAR(1)
VARCHAR2(15)
NUMBER(3,3)
EMPLOYEE
ID
STORE_NUMBER
PAY_TYPE_CODE
PAY_AMOUNT
TITLE
SUPERVISOR_ID
NUMBER
NUMBER
CHAR(1)
NUMBER(9,2)
VARCHAR2(15)
NUMBER
INVENTORY
PRODUCT_ID
STORE_NUMBER
QUANTITY_ON_HAND
QUANTITY_ON_ORDER
VARCHAR2(11)
NUMBER
NUMBER
NUMBER
ORDER_HEADER
INVOICE_NUMBER
STORE_NUMBER
CUSTOMER_ID
ACCOUNT_NUMBER
ORDER_DATE
EST_DELIVERY_DATE
DELIVERY_DATE
AMOUNT_DUE
NUMBER
NUMBER
NUMBER
NUMBER
DATE
DATE
DATE
NUMBER(9,2)
ORDER_ITEM
INVOICE_NUMBER
PRODUCT_ID
QUANTITY
DISCOUNT
NUMBER
VARCHAR2(11)
NUMBER
NUMBER(3,3)
PAY_TYPE
PAY_TYPE_CODE
PAY_TYPE_NAME
M INIMUM_WAGE
CHAR(1)
VARCHAR2(15)
NUMBER(9,2)
PERSON
ID
LASTNAME
FIRSTNAME
M I
STREET
CITY
STATE
ZIP
AREA_CODE
PHONE_NUMBER
NUMBER
VARCHAR2(25)
VARCHAR2(15)
CHAR(1)
VARCHAR2(45)
VARCHAR2(25)
CHAR(2)
CHAR(9)
CHAR(3)
CHAR(7)
PO_HEADER
PO_NUMBER
VENDOR_ID
STORE_NUMBER
ORDER_DATE
TAX_RATE
NUMBER
VARCHAR2(4)
NUMBER
DATE
NUMBER(5,5)
PO_ITEM
PO_NUMBER
VENDOR_PART_NUMBER
QUANTITY
UNIT_COST
PRODUCT_ID
NUMBER
VARCHAR2(20)
NUMBER
NUMBER(7,2)
VARCHAR2(11)
PRODUCT
PRODUCT_ID
DESCRIPTION
VENDOR_ID
VENDOR_PART_NUMBER
PRICE
REORDER_THRESHOLD
PRODUCT_CATEGORY_CODE
WARRANTY_TEXT
PRODUCT_IMAGE
VARCHAR2(11)
VARCHAR2(75)
VARCHAR2(4)
VARCHAR2(20)
NUMBER(7,2)
NUMBER
CHAR(1)
CLOB
BLOB
PRODUCT_CATEGORY
PRODUCT_CATEGORY_CODE
PRODUCT_CATEGORY_NAME
CHAR(1)
VARCHAR2(15)
STORE
STORE_NUMBER
MANAGER_ID
STREET
CITY
STATE
ZIP
AREA_CODE
PHONE_NUMBER
SALES_TAX_RATE
NUMBER
NUMBER
VARCHAR2(45)
VARCHAR2(25)
CHAR(2)
CHAR(9)
CHAR(3)
CHAR(7)
NUMBER(5,5)
VENDOR
VENDOR_ID
NAME
VENDOR_REP_ID
STREET
CITY
STATE
ZIP
COUNTRY
AREA_CODE
PHONE_NUMBER
VARCHAR2(4)
VARCHAR2(40)
NUMBER
VARCHAR2(45)
VARCHAR2(25)
CHAR(2)
CHAR(9)
VARCHAR2(15)
CHAR(3)
CHAR(7)
Introduction to Oracle 11g PL/SQL Programming
Page 18 Rev 05-14-09 © 2009 ITCourseware, LLC
© 2009 ITCourseware, LLC
ACCOUNT_TYPE_CODE = ACCOUNT_TYPE_CODE
ID = CUSTOMER_ID
ID = SUPERVISOR_ID
PAY_TYPE_CODE = PAY_TYPE_CODE
ID = ID
PRODUCT_ID = PRODUCT_ID
STORE_NUMBER = STORE_NUMBER
ACCOUNT_NUMBER = ACCOUNT_NUMBER
ID = CUSTOMER_ID
STORE_NUMBER = STORE_NUMBER
INVOICE_NUMBER = INVOICE_NUMBER
PRODUCT_ID = PRODUCT_ID
STORE_NUMBER = STORE_NUMBER
VENDOR_ID = VENDOR_ID
PO_NUMBER = PO_NUMBERPRODUCT_ID = PRODUCT_ID
PRODUCT_CATEGORY_CODE = PRODUCT_CATEGORY_CODE
VENDOR_ID = VENDOR_ID
ID = VENDOR_REP_ID
ACCOUNT
ACCOUNT_NUMBER
ACCOUNT_NAME
ACCOUNT_TYPE_CODE
CUSTOMER_ID
CREDIT_LIM IT
BALANCE
STREET
CITY
STATE
NUMBER
VARCHAR2(25)
CHAR(1)
NUMBER
NUMBER(9 ,2)
NUMBER(9 ,2 )
VARCHAR2(45)
VARCHAR2(25)
CHAR(2)
ACCOUNT_TYPE
ACCOUNT_TYPE_CODE
ACCOUNT_TYPE_NAME
INITIAL_DISCOUNT
CHAR(1)
VARCHAR2(15)
NUMBER(3 ,3 )
EMPLOYEE
ID
STORE_NUMBER
PAY_TYPE_CODE
PAY_AMOUNT
TITLE
SUPERVISOR_ID
NUMBER
NUMBER
CHAR(1)
NUMBER(9,2)
VARCHAR2(15)
NUMBER
INVENTORY
PRODUCT_ID
STORE_NUMBER
QUANTITY_ON_HAND
QUANTITY_ON_ORDER
VARCHAR2(11)
NUMBER
NUMBER
NUMBER
ORDER_HEADER
INVOICE_NUMBER
STORE_NUMBER
CUSTOMER_ID
ACCOUNT_NUMBER
ORDER_DATE
EST_DELIVERY_DATE
DELIVERY_DATE
AMOUNT_DUE
NUMBER
NUMBER
NUMBER
NUMBER
DATE
DATE
DATE
NUMBER(9,2)
ORDER_ITEM
INVOICE_NUMBER
PRODUCT_ID
QUANTITY
DISCOUNT
NUMBER
VARCHAR2(11)
NUMBER
NUMBER(3,3)
PAY_TYPE
PAY_TYPE_CODE
PAY_TYPE_NAME
MINIMUM_WAGE
CHAR(1)
VARCHAR2(15)
NUMBER(9,2)
PERSON
ID
LASTNAME
FIRSTNAME
MI
STREET
CITY
STATE
ZIP
AREA_CODE
PHONE_NUMBER
NUMBER
VARCHAR2(25)
VARCHAR2(15)
CHAR(1)
VARCHAR2(45)
VARCHAR2(25)
CHAR(2)
CHAR(9)
CHAR(3)
CHAR(7)
PO_HEADER
PO_NUMBER
VENDOR_ID
STORE_NUMBER
ORDER_DATE
TAX_RATE
NUMBER
VARCHAR2(4)
NUMBER
DATE
NUMBER(5,5)
PO_ITEM
PO_NUMBER
VENDOR_PART_NUMBER
QUANTITY
UNIT_COST
PRODUCT_ID
NUMBER
VARCHAR2(20)
NUMBER
NUMBER(7 ,2)
VARCHAR2(11)
PRODUCT
PRODUCT_ID
DESCRIPTION
VENDOR_ID
VENDOR_PART_NUMBER
PRICE
REORDER_THRESHOLD
PRODUCT_CATEGORY_CODE
WARRANTY_TEXT
PRODUCT_IMAGE
VARCHAR2(11)
VARCHAR2(75)
VARCHAR2(4)
VARCHAR2(20)
NUMBER(7 ,2 )
NUMBER
CHAR(1)
CLOB
BLOB
PRODUCT_CATEGORY
PRODUCT_CATEGORY_CODE
PRODUCT_CATEGORY_NAME
CHAR(1)
VARCHAR2(15)
STORE
STORE_NUMBER
MANAGER_ID
STREET
CITY
STATE
ZIP
AREA_CODE
PHONE_NUMBER
SALES_TAX_RATE
NUMBER
NUMBER
VARCHAR2(45)
VARCHAR2(25)
CHAR(2)
CHAR(9)
CHAR(3)
CHAR(7)
NUMBER(5,5)
VENDOR
VENDOR_ID
NAME
VENDOR_REP_ID
STREET
CITY
STATE
ZIP
COUNTRY
AREA_CODE
PHONE_NUMBER
VARCHAR2(4)
VARCHAR2(40)
NUMBER
VARCHAR2(45)
VARCHAR2(25)
CHAR(2)
CHAR(9)
VARCHAR2(15)
CHAR(3)
CHAR(7)
Introduction to Oracle 11g PL/SQL Programming
Page 20 Rev 05-14-09 © 2009 ITCourseware, LLC
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 91
Chapter 5 - Stored Procedures and Functions
Objectives
� Write and run stored procedures.
� Define stored procedure parameters,
with and without default values.
� Choose appropriate parameter
modes.
� Use named notation to invoke
subprograms with parameters in
arbitrary order.
� Provide default arguments for
parameters.
� Write and run stored functions.
� Run programs with invoker's rights
instead of definer's rights.
Introduction to Oracle 11g PL/SQL Programming
Page 92 Rev 05-14-09 © 2009 ITCourseware, LLC
� A PL/SQL program with no specification is called an anonymous block.
DECLARE
declarations
BEGIN
statements
END;
� Kept in script files, anonymous blocks are often used by DBAs and
developers for routine tasks.
� A trigger is a stored PL/SQL subprogram with a name:
CREATE TRIGGER triggername
{BEFORE|AFTER} {INSERT|UPDATE|DELETE}
ON tablename
DECLARE
declarations
BEGIN
statements
END;
� Compiled and stored in the system catalog, triggers are invoked (fired)
automatically, any time the specified DML statement happens.
� Stored functions and stored procedures are also named PL/SQL subprograms.
� Stored in the system catalog, stored functions and procedures are invoked
by name, from other subprograms or applications.
Stored Subprograms
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 93
anonymous.sqlDECLARE
lname VARCHAR2(25) := 'Grumby';
fname VARCHAR2(25) := 'Jonus';
BEGIN
INSERT INTO person(id, firstname, lastname)
VALUES (person_id_seq.NEXTVAL, fname, lname);
END;
/
Trigger:
person_id_check.sqlCREATE OR REPLACE TRIGGER person_id_check
BEFORE INSERT ON person
FOR EACH ROW
WHEN (new.id IS NULL)
BEGIN
:new.id := person_id_seq.NEXTVAL;
END;
/
DML which fires this trigger:
INSERT INTO person (firstname, lastname)
VALUES ('Fred', 'Dobbs')
Introduction to Oracle 11g PL/SQL Programming
Page 94 Rev 05-14-09 © 2009 ITCourseware, LLC
� A stored procedure's specification includes the procedure's name, as well as the
names and datatypes of any parameters:
CREATE [OR REPLACE] PROCEDURE procedurename
[(parm1 datatype1[, parm2 datatype2...])]
AS
[declarations]
BEGIN
statements
END;
� Parameters use unconstrained datatypes.
� Specify only the datatypes of parameters, such as NUMBER or
VARCHAR2; do not include the size.
� To create a procedure you must have the CREATE PROCEDURE privilege.
� Once created, a stored procedure is a permanent part of your schema.
Creating a Stored Procedure
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 95
The declaration section of a stored procedure begins with the word AS (or the word IS, whichever
you prefer):
create_account_type1.sqlCREATE OR REPLACE PROCEDURE create_account_type
(code CHAR, name VARCHAR2, disc NUMBER)
AS
BEGIN
INSERT INTO account_type
VALUES (code, name, disc);
END;
/
You can use anchored types in defining the formal parameters:
create_account_type2.sqlCREATE OR REPLACE PROCEDURE create_account_type
(code account_type.account_type_code%TYPE,
name account_type.account_type_name%TYPE,
disc account_type.initial_discount%TYPE)
AS
BEGIN
INSERT INTO account_type
VALUES (code, name, disc);
END;
/
Note:The SQL*Plus SHOW ERRORS command formats and prints errors from the most recent compilation of
a database object.
SQL> SHOW ERRORS
...
SQL> SHOW ERRORS PROCEDURE procedurename
...
SQL> SHOW ERRORS FUNCTION functionname
...
Introduction to Oracle 11g PL/SQL Programming
Page 96 Rev 05-14-09 © 2009 ITCourseware, LLC
Procedure Calls and Parameters
� A stored procedure can be called in any PL/SQL block invoked by a user with
EXECUTE privilege on the procedure.
BEGIN
create_account_type('F', 'Family', .10);
END;
� You can also execute a single PL/SQL statement or stored procedure in
SQL*Plus using the EXECUTE, or EXEC, command.
EXEC create_account_type('F', 'Family', .10);
� SQL*Plus just rewrites the EXECUTE statement as a
BEGIN...END; block.
� Parameters provide a mechanism for passing information in and out of
subprograms.
� They allow subprograms to be flexible.
� Inside of the procedure code, the parameters are used like local variables.
� When calling a stored procedure, parentheses are only used if there are values
being passed.
calculate_end_of_month;
� Arguments passed can be literal values or variables.
create_account_type(new_code, new_type, .10);
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 97
change_price.sqlCREATE OR REPLACE PROCEDURE change_price
(p_id product.product_id%TYPE, new_price product.price%TYPE)
AS
old_price product.price%TYPE;
BEGIN
SELECT price INTO old_price
FROM product
WHERE product_id = p_id;
IF ABS(new_price - old_price) < (old_price * 0.2) THEN
UPDATE product
SET price = new_price
WHERE product_id = p_id;
END IF;
END;
/
change_price_test.sqlDECLARE
prod product.product_id%TYPE;
price product.price%TYPE;
BEGIN
prod := 'XRX0000003';
price := 56.00;
change_price(prod, price); -- Pass variables
change_price('WDC0000020', 35.50); -- Pass literals
END;
/
Introduction to Oracle 11g PL/SQL Programming
Page 98 Rev 05-14-09 © 2009 ITCourseware, LLC
� A parameter's mode determines how a subprogram can use it.
... procedurename(paramname MODE datatype,...)
� IN mode (the default mode) allows a value to be passed in to the procedure.
� An IN mode parameter's initial value is taken from the value passed.
� The caller can pass a variable, literal, or expression.
� IN mode parameters are read-only (the subprogram can't assign to the
parameter variable); they act as constants.
� Since IN mode parameters are read-only they are passed by reference.
� OUT mode allows the procedure to place a value into the variable passed.
� OUT mode parameters have an initial value of NULL.
� The caller must pass a variable, not a literal or an expression.
� IN OUT mode allows an incoming value to be modified and passed back from
the procedure.
� An IN OUT mode parameter's initial value is the value of the variable
passed.
� The caller must pass a variable, not a literal or an expression.
� OUT and IN OUT parameters are passed by value, so the value of the argument
won't be changed in case of an exception.
� You cannot specify default values for OUT and IN OUT parameters.
Parameter Modes
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 99
Within a subprogram, an OUT mode parameter acts like an uninitialized variable:
get_manager_name.sqlCREATE OR REPLACE PROCEDURE get_manager_name
(store_no store.store_number%TYPE, manager_name OUT VARCHAR2)
AS
BEGIN
SELECT firstname || ' ' || lastname
INTO manager_name
FROM person INNER JOIN store ON (id = manager_id)
WHERE store_number = store_no;
END;
/
The actual parameters you pass to a procedure must be variables for OUT or IN OUT parameters:
manager_name_test.sqlVAR mname VARCHAR2(40)
DECLARE
name VARCHAR2(40);
BEGIN
get_manager_name(5,name);
:mname := name;
END;
/
PROMPT The manager for store number 5 is
PRINT mname
Note:According to the PL/SQL documentation, OUT mode parameters cannot be assigned from or used in
expressions; that is, they are "write-only." However, this restriction was relaxed in versions of Oracle above
7.3.4. You can now assign from OUT mode parameters and use them in expressions. Within the subprogram,
their initial value is NULL (regardless of the value of the variable passed as an actual parameter).
Introduction to Oracle 11g PL/SQL Programming
Page 100 Rev 05-14-09 © 2009 ITCourseware, LLC
Named Parameter Notation
� Up to now, we have been using positional notation for the actual parameters when
calling procedures and functions.
orders.count_po( '01-APR-96', '30-JUN-96', :second_quarter );
� The order of the actual parameters matches the order of the formal
parameters given in the specification.
� Using named notation, you may specify the actual parameters in any order.
count_po1( total => :first_quarter,
start_dt => '01-JAN-96', end_dt => '31-MAR-96');
� You may also mix both positional and named notation.
count_po1( '01-OCT-96', NULL, total => :last_quarter);
� Once you use named notation for one parameter, all subsequent parameters
in the list require named notation.
� You must use named notation if an overloaded function or procedure's signature is
not unique.
a := hr2.get_emps(state=>'CO');
a := hr2.get_emps(city=>'Denver');
� Subprograms can be overloaded if they are local to a block or declared
within a package.
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 101
orders1.sqlCREATE OR REPLACE PROCEDURE count_po1(
start_dt DATE, end_dt DATE, total OUT NUMBER)
AS
BEGIN
IF end_dt IS NULL THEN
SELECT count(po_number)
INTO total
FROM po_header
WHERE order_date >= start_dt;
ELSE
SELECT count(po_number)
INTO total
FROM po_header
WHERE order_date BETWEEN start_dt AND end_dt;
END IF;
END count_po1;
/
call_orders1.sqlVAR first_quarter NUMBER
VAR second_quarter NUMBER
VAR last_quarter NUMBER
VAR yearly_total NUMBER
BEGIN
count_po1( total => :first_quarter,
start_dt => '01-JAN-96', end_dt => '31-MAR-96');
count_po1( '01-APR-96', '30-JUN-96', :second_quarter );
count_po1( '01-OCT-96', NULL, total => :last_quarter);
count_po1( '01-JAN-96', NULL, total => :yearly_total );
END;
/
PRINT first_quarter
PRINT second_quarter
PRINT last_quarter
PRINT yearly_total
Introduction to Oracle 11g PL/SQL Programming
Page 102 Rev 05-14-09 © 2009 ITCourseware, LLC
Default Arguments
� You can specify a default value for IN mode parameters.
start_date DATE DEFAULT '01-JAN-96'
� If no actual parameter is passed, the formal parameter is initialized with the
default value.
� You can use the assignment operator instead of the word DEFAULT.
start_date DATE := '01-JAN-96'
� With default arguments, you can create stored procedures and functions that are
very flexible, allowing the caller to pass as many values as they need.
� In creating the parameter list, you should put the required arguments first, and
the ones that are most likely to have their defaults taken last.
CREATE OR REPLACE PROCEDURE count_po2(
total OUT NUMBER,
start_dt DATE DEFAULT '01-JAN-96',
end_dt DATE DEFAULT NULL)
� With this organization, it allows the caller to avoid the need for named
notation, as they can simply provide values from left to right.
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 103
orders2.sqlCREATE OR REPLACE PROCEDURE count_po2(
total OUT NUMBER,
start_dt DATE DEFAULT '01-JAN-96',
end_dt DATE DEFAULT NULL)
AS
BEGIN
IF end_dt IS NULL THEN
SELECT count(po_number)
INTO total
FROM po_header
WHERE order_date >= start_dt;
ELSE
SELECT count(po_number)
INTO total
FROM po_header
WHERE order_date BETWEEN start_dt AND end_dt;
END IF;
END count_po2;
/
call_orders2.sql
VAR first_quarter NUMBER
VAR second_quarter NUMBER
VAR last_quarter NUMBER
VAR yearly_total NUMBER
BEGIN
count_po2( :first_quarter, end_dt => '31-MAR-96');
count_po2( :second_quarter, '01-APR-96', '30-JUN-96' );
count_po2( :last_quarter, '01-OCT-96');
count_po2( :yearly_total );
END;
/
PRINT first_quarter
PRINT second_quarter
PRINT last_quarter
PRINT yearly_total
Introduction to Oracle 11g PL/SQL Programming
Page 104 Rev 05-14-09 © 2009 ITCourseware, LLC
� A function is like a procedure, but it returns a value:
CREATE [OR REPLACE] FUNCTION functionname
[(parm1 datatype1[, parm2 datatype2...])]
RETURN datatype
AS
[declarations]
BEGIN
statements
RETURN value;
END;
� If you're declaring a function, you must specify its return type, and it must
actually return a value of that type.
� The function body must contain a RETURN statement, which returns a value of
the specified type.
SELECT sales_tax_rate INTO rate FROM store
WHERE store_number = s;
RETURN rate;
� You can't create two stored functions, or a stored function and a stored
procedure, with the same name.
� Use CREATE OR REPLACE to redefine an existing function or
procedure.
CREATE OR REPLACE FUNCTION get_tax_rate(s NUMBER)
RETURN NUMBER AS ...
� As a general rule, functions should use only IN mode parameters.
� Use a function to take zero or more parameters, and compute and return
exactly one data item.
Creating a Stored Function
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 105
get_tax_rate.sqlCREATE OR REPLACE FUNCTION get_tax_rate (snum NUMBER)
RETURN NUMBER
AS
rate store.sales_tax_rate%TYPE;
BEGIN
SELECT sales_tax_rate INTO rate FROM store
WHERE store_number = snum;
RETURN rate;
END;
/
The following function will return the total for sales on a particular day. If a date is not provided, then the
current system date is used.
order_daily_total.sqlCREATE OR REPLACE FUNCTION order_daily_total
(in_date DATE DEFAULT SYSDATE)
RETURN NUMBER
AS
daily_total NUMBER;
BEGIN
SELECT sum(price * quantity) INTO daily_total
FROM product INNER JOIN order_item USING (product_id)
INNER JOIN order_header USING (invoice_number)
WHERE order_date = in_date;
RETURN daily_total;
END;
/
Introduction to Oracle 11g PL/SQL Programming
Page 106 Rev 05-14-09 © 2009 ITCourseware, LLC
� You can call a stored function, or a package function, in SQL statements (just
like a built-in function), if the function meets certain requirements, including:
� It must have only IN mode parameters.
� Parameters and the return value must have SQL datatypes;
BINARY_INTEGER or BOOLEAN, for example, are not allowed, nor
are record or collection types.
� In addition, a stored or package function called in SQL statements can have no
adverse side effects.
� It cannot update database data.
� If called anywhere other than a SELECT list, VALUES clause, or SET
clause, then it cannot change package variable values.
� It cannot call any functions or procedures that break these rules.
� The level of compliance with these and other restrictions is termed purity.
� The PL/SQL compiler determines the purity level of stand-alone stored
functions when they are compiled.
� Purity levels had to be asserted by the programmer, using PRAGMA
RESTRICT_REFERENCES, prior to Oracle 8i.
Stored Functions and SQL
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 107
get_tax_rate2.sqlSELECT sum(quantity * price * (1 + get_tax_rate(store_number)))
FROM order_header JOIN order_item USING (invoice_number)
JOIN product USING (product_id)
WHERE order_date = '01-MAR-96'
/
Oracle Database 10g (and earlier versions) allow only positional parameter notation when you call a stored
function from a SQL statement:
store_tax_rates1.sql
SELECT store_number, get_tax_rate(store_number)
FROM store
/
Starting with 11g, you can use named parameter notation when calling a stored function in SQL:
store_tax_rates2.sql
SELECT store_number, get_tax_rate(snum => store_number)
FROM store
/
Introduction to Oracle 11g PL/SQL Programming
Page 108 Rev 05-14-09 © 2009 ITCourseware, LLC
Invoker's Rights
� By default, stored PL/SQL program units execute with the privileges and schema
context of the creator of the unit, rather than the user who is executing the code.
� Use the AUTHID clause to override this default behavior.
AUTHID CURRENT_USER
� This signals that the program will execute using the rights of the user
currently executing the stored program.
� When the AUTHID clause is used for a package, it is defined in the package
specification and applies to all routines in the package.
� Priviliges are checked when executing a stored subprogram.
� Invoker's rights will require that the invoker (current user) has all of the
necessary privileges for the tables and other subprograms being
manipulated.
� Using the invoker's schema context means that object resolution will be based
on the invoker's schema, not the schema of the user that defined the
subprogram.
� Each user may have different synonyms, tables, and views defined.
� Make sure that tables and views are fully qualified with their schema
name to avoid confusion.
� You can explicitly specify the default behavior of definer's rights with the
AUTHID clause.
AUTHID DEFINER
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 109
Consider a procedure which updates an unqualified reference to emp.
With invoker's rights, a user would need to have the DELETE privilege on the emp table. And, the
resolution of emp would depend on the current user's schema definition.
delete_emp1.sqlCREATE OR REPLACE PROCEDURE delete_emp1 (in_empid NUMBER)
AUTHID CURRENT_USER IS
BEGIN
DELETE FROM emp
WHERE id = in_empid;
END;
/
The same procedure using definer's rights would not require the invoker to have the DELETE privilege on
emp, only the EXECUTE privilege on the procedure. Additionally, the resolution of emp would be based
on the schema of the procedure's creator, not the user running it.
delete_emp2.sqlCREATE OR REPLACE PROCEDURE delete_emp2 (in_empid NUMBER)
AUTHID DEFINER IS
BEGIN
DELETE FROM emp
WHERE id = in_empid;
END;
/
Try It:Log into the database as s1, and create a synonym of emp:
CREATE SYNONYM emp FOR employees;
Then, create each of the procedures above:
@delete_emp1
@delete_emp2
Grant EXECUTE privilege on these procedures to the s2 user:
GRANT EXECUTE ON delete_emp1 TO s2;
GRANT EXECUTE ON delete_emp2 TO s2;
Now log in as the s2 user and try executing each procedure:
EXEC s1.delete_emp1(8044); -- this call fails
EXEC s1.delete_emp2(8044); -- this call succeeds
Introduction to Oracle 11g PL/SQL Programming
Page 110 Rev 05-14-09 © 2009 ITCourseware, LLC
� Create a stored procedure named raise_pay that will increase an employee's pay amount. The
parameters should be the employee's id number and the percent increase to his salary. Use 3% as
the default percent increase.
(Solution: raise_pay.sql)
� Create a stored function called emp_count that returns a number. Allow the function to be called
with a state code as a parameter. If a state is provided, then return the number of employees in that
state. If no state is provided, then return the total number of employees.
(Solutions: emp_count.sql, emp_count_test.sql)
� Create a stored function called get_store that takes a city and state as its parameters and
returns a store number. Create an anonymous block of code to call this function on the Las Vegas,
NV store, putting the result into a bind variable.
(Solution: getstore.sql)
Labs
Stored Procedures and FunctionsChapter 5
© 2009 ITCourseware, LLC Rev 05-14-09 Page 111