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 toOracle 11g PL/SQL
Programming
Student Workbook
Page ii Rev 1.1.2 © 2011 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 thisworkbook, including Roger Jones, Jim McNally, and Kevin Smith, and the many students who have offeredcomments, suggestions, criticisms, and insights.
Copyright © 2011 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced orutilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or by aninformation storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed 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 respectiveowners.
© 2011 ITCourseware, LLC Rev 1.1.2 Page iii
Introduction to Oracle 11g PL/SQL Programming
Contents
Chapter 1 - Course Introduction ............................................................................................................... 9
Course Objectives ............................................................................................................................ 10Course Overview .............................................................................................................................. 12Using the Workbook ......................................................................................................................... 13Suggested References ....................................................................................................................... 14Sample Database .............................................................................................................................. 16
Chapter 2 - Triggers ................................................................................................................................ 21
Beyond Declarative Integrity ............................................................................................................. 22Triggers ............................................................................................................................................. 24Types of Triggers ............................................................................................................................... 26Trigger Sequencing ............................................................................................................................ 28Row-Level Triggers........................................................................................................................... 30Trigger Predicates ............................................................................................................................. 32
............................................................................................................................................................................................. 32
............................................................................................................................................................................................. 32
............................................................................................................................................................................................. 32
............................................................................................................................................................................................. 32Trigger Conditions ............................................................................................................................. 34Using SEQUENCEs ......................................................................................................................... 36
............................................................................................................................................................................................. 36
............................................................................................................................................................................................. 36
............................................................................................................................................................................................. 36Cascading Triggers and Mutating Tables ............................................................................................ 38Generating an Error ........................................................................................................................... 40Maintaining Triggers .......................................................................................................................... 42Labs ................................................................................................................................................. 44
Chapter 3 - PL/SQL Variables and Datatypes ......................................................................................... 47
Anonymous Blocks ........................................................................................................................... 48Declaring Variables ............................................................................................................................ 50Datatypes.......................................................................................................................................... 52Subtypes ........................................................................................................................................... 54Character Data ................................................................................................................................. 56Dates and Timestamps ...................................................................................................................... 58
Page iv Rev 1.1.2 © 2011 ITCourseware, LLC
Introduction to Oracle 11g PL/SQL Programming
Date Intervals .................................................................................................................................... 60Anchored Types ................................................................................................................................ 62Assignment and Conversions ............................................................................................................. 64Selecting into a Variable .................................................................................................................... 66Returning into a Variable .................................................................................................................... 68Labs ................................................................................................................................................. 70
Chapter 4 - PL/SQL Syntax and Logic ................................................................................................... 73
Conditional Statements — IF/THEN................................................................................................. 74Conditional Statements — CASE ..................................................................................................... 76Comments and Labels ....................................................................................................................... 78Loops ............................................................................................................................................... 80WHILE and FOR Loops .................................................................................................................. 82SQL in PL/SQL ................................................................................................................................ 84Local Procedures and Functions ....................................................................................................... 86Labs ................................................................................................................................................. 88
Chapter 5 - Stored Procedures and Functions ......................................................................................... 91
Stored Subprograms ......................................................................................................................... 92Creating a Stored Procedure ............................................................................................................. 94Procedure Calls and Parameters ....................................................................................................... 96Parameter Modes ............................................................................................................................. 98Named Parameter Notation ............................................................................................................ 100Default Arguments ........................................................................................................................... 102Creating a Stored Function .............................................................................................................. 104Stored Functions and SQL.............................................................................................................. 106Invoker's Rights .............................................................................................................................. 108Labs ............................................................................................................................................... 110
Chapter 6 - Exception Handling ............................................................................................................ 113
SQLCODE and SQLERRM .......................................................................................................... 114Exception Handlers ......................................................................................................................... 116Nesting Blocks ................................................................................................................................ 118Scope and Name Resolution ........................................................................................................... 120Declaring and Raising Named Exceptions ........................................................................................ 122User-Defined Exceptions ................................................................................................................ 124Labs ............................................................................................................................................... 126
© 2011 ITCourseware, LLC Rev 1.1.2 Page v
Introduction to Oracle 11g PL/SQL Programming
Chapter 7 - Records, Collections, and User-Defined Types .................................................................. 129
Record Variables ............................................................................................................................. 130Using the %ROWTYPE Attribute ................................................................................................... 132User-Defined Object Types ............................................................................................................ 134VARRAY and Nested TABLE Collections ...................................................................................... 136Using Nested TABLEs .................................................................................................................... 138Using VARRAYs ............................................................................................................................ 140Collections in Database Tables ........................................................................................................ 142Associative Array Collections .......................................................................................................... 144Collection Methods ......................................................................................................................... 146Iterating Through Collections ........................................................................................................... 148Labs ............................................................................................................................................... 150
Chapter 8 - Cursors .............................................................................................................................. 153
Multi-Row Queries ......................................................................................................................... 154Declaring and Opening Cursors ....................................................................................................... 156Fetching Rows ................................................................................................................................ 158Closing Cursors .............................................................................................................................. 160The Cursor FOR Loop ................................................................................................................... 162FOR UPDATE Cursors .................................................................................................................. 164Cursor Parameters .......................................................................................................................... 166The Implicit (SQL) Cursor .............................................................................................................. 168Labs ............................................................................................................................................... 170
Chapter 9 - Bulk Operations ................................................................................................................. 173
Bulk Binding ................................................................................................................................... 174BULK COLLECT Clause .............................................................................................................. 176FORALL Statement ........................................................................................................................ 178FORALL Variations ........................................................................................................................ 180Bulk Returns ................................................................................................................................... 182Bulk Fetching with Cursors ............................................................................................................. 184Labs ............................................................................................................................................... 186
Chapter 10 - Using Packages ................................................................................................................ 189
Packages ........................................................................................................................................ 190Oracle-Supplied Packages .............................................................................................................. 192The DBMS_OUTPUT Package ..................................................................................................... 194The DBMS_UTILITY Package ...................................................................................................... 196
Page vi Rev 1.1.2 © 2011 ITCourseware, LLC
Introduction to Oracle 11g PL/SQL Programming
The UTL_FILE Package ................................................................................................................ 198Creating Pipes with DBMS_PIPE ................................................................................................... 200Writing to and Reading from a Pipe ................................................................................................. 202The DBMS_METADATA Package ................................................................................................ 204XML Packages ............................................................................................................................... 206Networking Packages ..................................................................................................................... 208Other Supplied Packages ................................................................................................................ 210Labs ............................................................................................................................................... 212
Chapter 11 - Creating Packages ............................................................................................................ 215
Structure of a Package .................................................................................................................... 216The Package Interface and Implementation ..................................................................................... 218Package Variables and Package State ............................................................................................. 220Overloading Package Functions and Procedures ............................................................................. 222Forward Declarations ..................................................................................................................... 224Strong REF CURSOR Variables ..................................................................................................... 226Weak REF CURSOR Variables ...................................................................................................... 228Labs ............................................................................................................................................... 230
Chapter 12 - Working with LOBs ......................................................................................................... 233
Large Object Types ........................................................................................................................ 234Oracle Directories ........................................................................................................................... 236LOB Locators ................................................................................................................................ 238Internal LOBs ................................................................................................................................. 240LOB Storage and SECUREFILEs .................................................................................................. 242External LOBs ................................................................................................................................ 244Temporary LOBs ............................................................................................................................ 246The DBMS_LOB Package ............................................................................................................. 248Labs ............................................................................................................................................... 250
Chapter 13 - Maintaining PL/SQL Code ............................................................................................... 253
Privileges for Stored Programs ........................................................................................................ 254Data Dictionary ............................................................................................................................... 256PL/SQL Stored Program Compilation ............................................................................................. 258Conditional Compilation .................................................................................................................. 260Compile-Time Warnings .................................................................................................................. 262The PL/SQL Execution Environment ............................................................................................... 264Dependencies and Validation ........................................................................................................... 266Maintaining Stored Programs .......................................................................................................... 268
© 2011 ITCourseware, LLC Rev 1.1.2 Page vii
Introduction to Oracle 11g PL/SQL Programming
Labs ............................................................................................................................................... 270
Appendix A - Dynamic SQL ................................................................................................................. 273
Generating SQL at Runtime ............................................................................................................. 274Native Dynamic SQL vs. DBMS_SQL Package ............................................................................. 276The EXECUTE IMMEDIATE Statement ........................................................................................ 278Using Bind Variables ....................................................................................................................... 280Multi-row Dynamic Queries ............................................................................................................ 282Bulk Operations with Dynamic SQL ............................................................................................... 284Using DBMS_SQL......................................................................................................................... 286DBMS_SQL Subprograms ............................................................................................................. 288
Appendix B - PL/SQL Versions, Datatypes and Language Limits .......................................................... 291
Solutions ............................................................................................................................................... 299
Index..................................................................................................................................................... 331
Page viii Rev 1.1.2 © 2011 ITCourseware, LLC
Introduction to Oracle 11g PL/SQL Programming
Course IntroductionChapter 1
© 2011 ITCourseware, LLC Rev 1.1.2 Page 9
Chapter 1 - Course Introduction
Introduction to Oracle 11g PL/SQL Programming
Page 10 Rev 1.1.2 © 2011 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
© 2011 ITCourseware, LLC Rev 1.1.2 Page 11
Introduction to Oracle 11g PL/SQL Programming
Page 12 Rev 1.1.2 © 2011 ITCourseware, LLC
Audience: This course is designed for database application developersprogramming in an Oracle environment.
Prerequisites: A working knowledge of the SQL language, as well as a solidunderstanding of 3GL programming is required.
Classroom Environment:
One workstation per student.
Oracle Server and SQL*Plus.
Course Overview
Course IntroductionChapter 1
© 2011 ITCourseware, LLC Rev 1.1.2 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 youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. 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 ason-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 providesthe main topics for
classroom discussion.
The Support page hasadditional information,
examples and suggestions.
Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.
Screen shots showexamples of what youshould see in class.
Topics are organized intofirst ( ), second ( ) and
third ( ) level points.
Pages are numberedsequentially throughoutthe book, making lookup
easy.
Callout boxes point outimportant parts of the
example code.
Introduction to Oracle 11g PL/SQL Programming
Page 14 Rev 1.1.2 © 2011 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 WebApplication 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 andAssociates, 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 andAssociates, 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
© 2011 ITCourseware, LLC Rev 1.1.2 Page 15
Rosenzweig, Benjamin and Elena Silvestrova Rakhimov. 2008. Oracle PL/SQL by Example. Prentice HallPTR, 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.comwww.oracle.com/technology/tech/pl_sqltahiti.oracle.com
Introduction to Oracle 11g PL/SQL Programming
Page 16 Rev 1.1.2 © 2011 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 isan employee, we must record in which store he or she works, the supervisor's ID, theemployees's title, pay amount, and compensation type ("Hourly," "Salaried," etc.)
Sometimes a customer will fill out an order, which requires an invoice number. Eachinvoice lists the store and the customer's ID. We record the quantity of each item onthe invoice and any discount for that item. We also keep track of how much thecustomer has paid on the order.
When a credit account is used for an order, the balance for the account must beupdated to reflect the total amount of the invoice (including tax). The salespersonverifies (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 ofthe 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 salesrep ID for each individual vendor.
We keep track of how many items are on hand at each store and how many each storehas on order. When an item is sold, the inventory is updated.
We maintain the address, phone number, and manager ID for each store. Each storehas 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 purchaseorder in our company has a unique PO number. A PO is sent to a single vendor, fromwhich we might be ordering several items, each at a specific unit cost. The inventoryreflects the sale or order of any item in a store.
Course IntroductionChapter 1
© 2011 ITCourseware, LLC Rev 1.1.2 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_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_NUMBERACCOUNT_NAMEACCOUNT_TYPE_CODECUSTOMER_IDCREDIT_LIMITBALANCESTREETCITYSTATE
NUMBERVARCHAR2(25)CHAR(1)NUMBERNUMBER(9,2)NUMBER(9,2)VARCHAR2(45)VARCHAR2(25)CHAR(2)
ACCOUNT_TYPE
ACCOUNT_TYPE_CODEACCOUNT_TYPE_NAMEINIT IAL_DISCOUNT
CHAR(1)VARCHAR2(15)NUMBER(3,3)
EMPLOYEE
IDSTORE_NUMBERPAY_TYPE_CODEPAY_AMOUNTTITLESUPERVISOR_ID
NUMBERNUMBERCHAR(1)NUMBER(9,2)VARCHAR2(15)NUMBER
INVENTORY
PRODUCT_IDSTORE_NUMBERQUANTITY_ON_HANDQUANTITY_ON_ORDER
VARCHAR2(11)NUMBERNUMBERNUMBER
ORDER_HEADER
INVOICE_NUMBERSTORE_NUMBERCUSTOMER_IDACCOUNT_NUMBERORDER_DATEEST_DELIVERY_DATEDELIVERY_DATEAMOUNT_DUE
NUMBERNUMBERNUMBERNUMBERDATEDATEDATENUMBER(9,2)
ORDER_ITEM
INVOICE_NUMBERPRODUCT_IDQUANTITYDISCOUNT
NUMBERVARCHAR2(11)NUMBERNUMBER(3,3)
PAY_TYPE
PAY_TYPE_CODEPAY_TYPE_NAMEMINIMUM_WAGE
CHAR(1)VARCHAR2(15)NUMBER(9,2)
PERSON
IDLASTNAMEFIRSTNAMEMISTREETCITYSTATEZIPAREA_CODEPHONE_NUMBER
NUMBERVARCHAR2(25)VARCHAR2(15)CHAR(1)VARCHAR2(45)VARCHAR2(25)CHAR(2)CHAR(9)CHAR(3)CHAR(7)
PO_HEADER
PO_NUMBERVENDOR_IDSTORE_NUMBERORDER_DATETAX_RATE
NUMBERVARCHAR2(4)NUMBERDATENUMBER(5,5)
PO_ITEM
PO_NUMBERVENDOR_PART_NUMBERQUANTITYUNIT_COSTPRODUCT_ID
NUMBERVARCHAR2(20)NUMBERNUMBER(7,2)VARCHAR2(11)
PRODUCT
PRODUCT_IDDESCRIPT IONVENDOR_IDVENDOR_PART_NUMBERPRICEREORDER_THRESHOLDPRODUCT_CATEGORY_CODEWARRANTY_TEXTPRODUCT_IMAGE
VARCHAR2(11)VARCHAR2(75)VARCHAR2(4)VARCHAR2(20)NUMBER(7,2)NUMBERCHAR(1)CLOBBLOB
PRODUCT_CATEGORY
PRODUCT_CATEGORY_CODEPRODUCT_CATEGORY_NAME
CHAR(1)VARCHAR2(15)
STORE
STORE_NUMBERMANAGER_IDSTREETCITYSTATEZIPAREA_CODEPHONE_NUMBERSALES_TAX_RATE
NUMBERNUMBERVARCHAR2(45)VARCHAR2(25)CHAR(2)CHAR(9)CHAR(3)CHAR(7)NUMBER(5,5)
VENDOR
VENDOR_IDNAMEVENDOR_REP_IDSTREETCITYSTATEZIPCOUNTRYAREA_CODEPHONE_NUMBER
VARCHAR2(4)VARCHAR2(40)NUMBERVARCHAR2(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_NUMBERACCOUNT_NAMEACCOUNT_TYPE_CODECUSTOMER_IDCREDIT_LIMITBALANCESTREETCITYSTATE
NUMBERVARCHAR2(25)CHAR(1)NUMBERNUMBER(9,2)NUMBER(9,2)VARCHAR2(45)VARCHAR2(25)CHAR(2)
ACCOUNT_TYPE
ACCOUNT_TYPE_CODEACCOUNT_TYPE_NAMEINIT IAL_DISCOUNT
CHAR(1)VARCHAR2(15)NUMBER(3,3)
EMPLOYEE
IDSTORE_NUMBERPAY_TYPE_CODEPAY_AMOUNTTITLESUPERVISOR_ID
NUMBERNUMBERCHAR(1)NUMBER(9,2)VARCHAR2(15)NUMBER
INVENTORY
PRODUCT_IDSTORE_NUMBERQUANTITY_ON_HANDQUANTITY_ON_ORDER
VARCHAR2(11)NUMBERNUMBERNUMBER
ORDER_HEADER
INVOICE_NUMBERSTORE_NUMBERCUSTOMER_IDACCOUNT_NUMBERORDER_DATEEST_DELIVERY_DATEDELIVERY_DATEAMOUNT_DUE
NUMBERNUMBERNUMBERNUMBERDATEDATEDATENUMBER(9,2)
ORDER_ITEM
INVOICE_NUMBERPRODUCT_IDQUANTITYDISCOUNT
NUMBERVARCHAR2(11)NUMBERNUMBER(3,3)
PAY_TYPE
PAY_TYPE_CODEPAY_TYPE_NAMEMINIMUM_WAGE
CHAR(1)VARCHAR2(15)NUMBER(9,2)
PERSON
IDLASTNAMEFIRSTNAMEMISTREETCITYSTATEZIPAREA_CODEPHONE_NUMBER
NUMBERVARCHAR2(25)VARCHAR2(15)CHAR(1)VARCHAR2(45)VARCHAR2(25)CHAR(2)CHAR(9)CHAR(3)CHAR(7)
PO_HEADER
PO_NUMBERVENDOR_IDSTORE_NUMBERORDER_DATETAX_RATE
NUMBERVARCHAR2(4)NUMBERDATENUMBER(5,5)
PO_ITEM
PO_NUMBERVENDOR_PART_NUMBERQUANTITYUNIT_COSTPRODUCT_ID
NUMBERVARCHAR2(20)NUMBERNUMBER(7,2)VARCHAR2(11)
PRODUCT
PRODUCT_IDDESCRIPT IONVENDOR_IDVENDOR_PART_NUMBERPRICEREORDER_THRESHOLDPRODUCT_CATEGORY_CODEWARRANTY_TEXTPRODUCT_IMAGE
VARCHAR2(11)VARCHAR2(75)VARCHAR2(4)VARCHAR2(20)NUMBER(7,2)NUMBERCHAR(1)CLOBBLOB
PRODUCT_CATEGORY
PRODUCT_CATEGORY_CODEPRODUCT_CATEGORY_NAME
CHAR(1)VARCHAR2(15)
STORE
STORE_NUMBERMANAGER_IDSTREETCITYSTATEZIPAREA_CODEPHONE_NUMBERSALES_TAX_RATE
NUMBERNUMBERVARCHAR2(45)VARCHAR2(25)CHAR(2)CHAR(9)CHAR(3)CHAR(7)NUMBER(5,5)
VENDOR
VENDOR_IDNAMEVENDOR_REP_IDSTREETCITYSTATEZIPCOUNTRYAREA_CODEPHONE_NUMBER
VARCHAR2(4)VARCHAR2(40)NUMBERVARCHAR2(45)VARCHAR2(25)CHAR(2)CHAR(9)VARCHAR2(15)CHAR(3)CHAR(7)
Introduction to Oracle 11g PL/SQL Programming
Page 20 Rev 1.1.2 © 2011 ITCourseware, LLC
Stored Procedures and FunctionsChapter 5
© 2011 ITCourseware, LLC Rev 1.1.2 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 parametermodes.
Use named notation to invokesubprograms with parameters inarbitrary order.
Provide default arguments forparameters.
Write and run stored functions.
Run programs with invoker's rightsinstead of definer's rights.
Introduction to Oracle 11g PL/SQL Programming
Page 92 Rev 1.1.2 © 2011 ITCourseware, LLC
A PL/SQL program with no specification is called an anonymous block.
DECLAREdeclarations
BEGINstatements
END;
Kept in script files, anonymous blocks are often used by DBAs anddevelopers for routine tasks.
A trigger is a stored PL/SQL subprogram with a name:
CREATE TRIGGER triggername{BEFORE|AFTER} {INSERT|UPDATE|DELETE}ON tablename
DECLAREdeclarations
BEGINstatements
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 invokedby name, from other subprograms or applications.
Stored Subprograms
Stored Procedures and FunctionsChapter 5
© 2011 ITCourseware, LLC Rev 1.1.2 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 1.1.2 © 2011 ITCourseware, LLC
A stored procedure's specification includes the procedure's name, as well as thenames and datatypes of any parameters:
CREATE [OR REPLACE] PROCEDURE procedurename[(parm1 datatype1[, parm2 datatype2...])]
AS[declarations]
BEGINstatements
END;
Parameters use unconstrained datatypes.
Specify only the datatypes of parameters, such as NUMBER orVARCHAR2; 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
© 2011 ITCourseware, LLC Rev 1.1.2 Page 95
The declaration section of a stored procedure begins with the word AS (or the word IS, whicheveryou prefer):
create_account_type1.sqlCREATE OR REPLACE PROCEDURE create_account_type
(code CHAR, name VARCHAR2, disc NUMBER)ASBEGIN
INSERT INTO account_typeVALUES (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)ASBEGIN 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 ofa 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 1.1.2 © 2011 ITCourseware, LLC
Procedure Calls and Parameters
A stored procedure can be called in any PL/SQL block invoked by a user withEXECUTE privilege on the procedure.
BEGIN create_account_type('F', 'Family', .10);END;
You can also execute a single PL/SQL statement or stored procedure inSQL*Plus using the EXECUTE, or EXEC, command.
EXEC create_account_type('F', 'Family', .10);
SQL*Plus just rewrites the EXECUTE statement as aBEGIN...END; block.
Parameters provide a mechanism for passing information in and out ofsubprograms.
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 valuesbeing 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
© 2011 ITCourseware, LLC Rev 1.1.2 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 literalsEND;/
Introduction to Oracle 11g PL/SQL Programming
Page 98 Rev 1.1.2 © 2011 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 theparameter 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 fromthe procedure.
An IN OUT mode parameter's initial value is the value of the variablepassed.
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 argumentwon'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
© 2011 ITCourseware, LLC Rev 1.1.2 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)ASBEGIN 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 inexpressions; that is, they are "write-only." However, this restriction was relaxed in versions of Oracle above7.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 1.1.2 © 2011 ITCourseware, LLC
Named Parameter Notation
Up to now, we have been using positional notation for the actual parameters whencalling 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 formalparameters 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 parametersin the list require named notation.
You must use named notation if an overloaded function or procedure's signature isnot 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 declaredwithin a package.
Stored Procedures and FunctionsChapter 5
© 2011 ITCourseware, LLC Rev 1.1.2 Page 101
orders1.sqlCREATE OR REPLACE PROCEDURE count_po1( start_dt DATE, end_dt DATE, total OUT NUMBER)ASBEGIN 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 NUMBERVAR second_quarter NUMBERVAR last_quarter NUMBERVAR 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_quarterPRINT second_quarterPRINT last_quarterPRINT yearly_total
Introduction to Oracle 11g PL/SQL Programming
Page 102 Rev 1.1.2 © 2011 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 thedefault 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 arevery flexible, allowing the caller to pass as many values as they need.
In creating the parameter list, you should put the required arguments first, andthe 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 namednotation, as they can simply provide values from left to right.
Stored Procedures and FunctionsChapter 5
© 2011 ITCourseware, LLC Rev 1.1.2 Page 103
orders2.sqlCREATE OR REPLACE PROCEDURE count_po2( total OUT NUMBER, start_dt DATE DEFAULT '01-JAN-96', end_dt DATE DEFAULT NULL)ASBEGIN 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.sqlVAR first_quarter NUMBERVAR second_quarter NUMBERVAR last_quarter NUMBERVAR 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_quarterPRINT second_quarterPRINT last_quarterPRINT yearly_total
Introduction to Oracle 11g PL/SQL Programming
Page 104 Rev 1.1.2 © 2011 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]
BEGINstatementsRETURN value;
END;
If you're declaring a function, you must specify its return type, and it mustactually return a value of that type.
The function body must contain a RETURN statement, which returns a value ofthe 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 storedprocedure, with the same name.
Use CREATE OR REPLACE to redefine an existing function orprocedure.
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 returnexactly one data item.
Creating a Stored Function
Stored Procedures and FunctionsChapter 5
© 2011 ITCourseware, LLC Rev 1.1.2 Page 105
get_tax_rate.sqlCREATE OR REPLACE FUNCTION get_tax_rate (snum NUMBER) RETURN NUMBERAS 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 thecurrent system date is used.
order_daily_total.sqlCREATE OR REPLACE FUNCTION order_daily_total
(in_date DATE DEFAULT SYSDATE)RETURN NUMBER
ASdaily_total NUMBER;
BEGINSELECT 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 1.1.2 © 2011 ITCourseware, LLC
You can call a stored function, or a package function, in SQL statements (justlike 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, norare record or collection types.
In addition, a stored or package function called in SQL statements can have noadverse side effects.
It cannot update database data.
If called anywhere other than a SELECT list, VALUES clause, or SETclause, 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 storedfunctions when they are compiled.
Purity levels had to be asserted by the programmer, using PRAGMARESTRICT_REFERENCES, prior to Oracle 8i.
Stored Functions and SQL
Stored Procedures and FunctionsChapter 5
© 2011 ITCourseware, LLC Rev 1.1.2 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 storedfunction from a SQL statement:
store_tax_rates1.sqlSELECT 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.sqlSELECT store_number, get_tax_rate(snum => store_number) FROM store/
Introduction to Oracle 11g PL/SQL Programming
Page 108 Rev 1.1.2 © 2011 ITCourseware, LLC
Invoker's Rights
By default, stored PL/SQL program units execute with the privileges and schemacontext 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 usercurrently executing the stored program.
When the AUTHID clause is used for a package, it is defined in the packagespecification 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 thenecessary privileges for the tables and other subprograms beingmanipulated.
Using the invoker's schema context means that object resolution will be basedon the invoker's schema, not the schema of the user that defined thesubprogram.
Each user may have different synonyms, tables, and views defined.
Make sure that tables and views are fully qualified with their schemaname to avoid confusion.
You can explicitly specify the default behavior of definer's rights with theAUTHID clause.
AUTHID DEFINER
Stored Procedures and FunctionsChapter 5
© 2011 ITCourseware, LLC Rev 1.1.2 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, theresolution 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 ISBEGIN 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 onemp, only the EXECUTE privilege on the procedure. Additionally, the resolution of emp would be basedon 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 ISBEGIN 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 failsEXEC s1.delete_emp2(8044); -- this call succeeds
Introduction to Oracle 11g PL/SQL Programming
Page 110 Rev 1.1.2 © 2011 ITCourseware, LLC
Create a stored procedure named raise_pay that will increase an employee's pay amount. Theparameters should be the employee's id number and the percent increase to his salary. Use 3% asthe default percent increase.(Solution: raise_pay.sql)
Create a stored function called emp_count that returns a number. Allow the function to be calledwith a state code as a parameter. If a state is provided, then return the number of employees in thatstate. 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 andreturns 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
© 2011 ITCourseware, LLC Rev 1.1.2 Page 111
Introduction to Oracle 11g PL/SQL Programming
Page 112 Rev 1.1.2 © 2011 ITCourseware, LLC