Achieving PL/SQL Excellence

Oracle PL/SQL Advanced Techniques
Oracle7 thru Oracle8i
Steven Feuerstein
www.StevenFeuerstein.com www.Quest.com www.OReilly.com
and contributions most excellent from Bill Pribyl and Dick Bolz

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 1

Objective & Outline 

Objective
± Expand your knowledge and awareness of important and new features of the PL/SQL language. 

Outline
± ± ± ± ± ± ± ± Building with Packages (Oracle7+) PL/SQL Collections (Oracle7 and Oracle8+) Cursor Variables (Oracle7 and Oracle8+) Dynamic SQL: DBMS_SQL and Native Dynamic SQL (8i) Calling Java from PL/SQL (Oracle8i) and C (Oracle8) Oracle Advanced Queuing with DBMS_AQ (Oracle8) Managing Large Objects with DBMS_LOB (Oracle8) Other Oracle8i New Features
» Autonomous Transactions (Oracle8i) » Invoker Rights Model (Oracle8i) » Row Level Security: DBMS_RLS

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 2

Software Used in Training 

PL/Vision: a library of packages installed on top of PL/SQL.
± PL/Vision Lite - use it, copy, change it for free -- unless you build software to be sold commercially. ± Active PL/SQL Knowledge Base: contains PL/Vision Professional, the fully supported and enhanced version. 

Demonstration scripts executed in the training can be found on the RevealNet PL/SQL Pipeline:
± http://www.revealnet.com/Pipelines/PLSQL/index.htm ± Archives surfboard, Miscellaneous, PL/SQL Seminar Files ± See filedesc.doc for a listing of many of the files.
plsql_ides.txt 

The PL/SQL IDE (Integrated Development Environment).
± You no longer have to use SQL*Plus and a crude editor! Choose from among the many listed in plsql_ides.txt.

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 3

Achieving PL/SQL Excellence

Building with PL/SQL Packages 
 

Overview Initialization section Overloading

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 4

What is a Package? 

A collection of code elements, from procedures and functions to TYPE, variable and cursor declarations.
± Single-most important structure within PL/SQL, and almost certainly one of the most under-utilized. ± Conceptually very simple, it can take some time to fully grasp the implications and potential of the package. 

The method of choice by Oracle and other software developers for extending the PL/SQL language.
± You will find packages in the database, in Oracle Developer/2000, in Oracle Application Server. 

Let¶s review some of the benefits of packages.
tmr.pkg dbparm.pkg

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 5

pkg  Improve transaction integrity by hiding data structures behind the package interface.When to Build a Package  Join physically logically-related code.pks te_employee. watch.page 6 . you call the packaged procedures and functions instead. ± There's a big difference between a bunch of separate programs and a coherent. package-based "component". ± Puts more structure and organization in your body of code.pkg 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Instead of writing SQL directly in your programs. custrules.pkb  Construct very flexible and usable utilities for developers. ± Can lead to performance improvements.pkg insga. te_employee.

page 7 . ± The PL/SQL runtime engine determines when and if this code should be run. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . the first time any package element is referenced. Does the package have an init section? yes Run initialization code.Package Initialization  The initialization section is a block of code at the end of the package body that is executed once per session. Program references package element the first time in each session. no Complete request for packaged element.

PACKAGE BODY pkg IS PROCEDURE proc IS BEGIN END.page 8 . FUNCTION func RETURN BEGIN END. BEGIN END pkg.Package Initialization Structure  The initialization section: ± Is defined after and outside of any programs in the package. PL/SQL Advanced Techniques .  Useful for: ± Performing complex setting of default or initial values. 1/21/2011 Copyright 2001 Steven Feuerstein BEGIN after/outside of any program defined in the pkg. In fact. ± Is not required. ± Confirming that package is properly instantiated. ± Can have its own exception handling section. ± Setting up package data which does not change for the duration of a session. most packages you build won't have one.

defprinter INTO show_lov. printer VARCHAR2(60). 'No profile for ' || USER). PL/SQL Advanced Techniques . show_toolbar CHAR(1). */ SELECT lov_flag. END sessinit. show_toolbar. tb_flag.page 9 1/21/2011 Copyright 2001 Steven Feuerstein .pkg init.tst this user.. 'Y'.. init.  Also a package with many design flaws. Section  An unusual package! ± Specification contains only variables. EXCEPTION WHEN NO_DATA_FOUND THEN /* No record for show_lov := show_toolbar := printer := PACKAGE sessinit IS show_lov CHAR(1). */ 'Y'.Configure Session with Init. ± Body contains only initialization section. END sessinit. WHEN OTHERS THEN RAISE_APPLICATION_ERROR (-20000. PACKAGE BODY sessinit IS /* No declared package elements at all! */ BEGIN /* Get user preferences for this user. 'lpt1'. printer FROM user_config WHERE user_id = USER.

Initialization section populates a PL/SQL table. BEGIN fmts(1) := 'DD-MON-RR'. fmts(4) := 'MM/DD'. fmts(3) := 'DD-MON'. datemgr. END dt.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . fmts(11) := 'YYYYMMDD'.Populate Collections  The PL/Vision Date package... . fmts(12) := 'RRMMDD'.pkg file demonstrates the basic technique (and the reliance on an initialization section) used to achieve this flexibility. fmts(9) := 'MM/DD/YYYY'.page 10 . fmts(10) := 'MMDDYYYY'.pkg dates. ± The datemgr. fmt_count := 12. PLVdate. ± This increases the flexibility of the date conversion process. employs several PL/SQL tables to convert strings and to perform date arithmetic. fmts(2) := 'DD-MON-YYYY'.

you need to make that code as smart and as easy to use as possible. myproc  Overloading is a critical feature when building comprehensive programmatic interfaces (APIs) or components using packages. you give two or more programs the same name.Program Overloading  When you overload programs. ± If you want others to use your code. ± Overloading transfers the "need to know" from the user to the overloaded program. myproc myproc 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± You can overload modules in any declaration section and in packages.page 11 .

number_string := TO_CHAR (10000). and took functions like TO_CHAR and TO_DATE totally for granted. number_string := TO_CHAR_FROM_NUMBER (10000). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± But Oracle couldn't offer that level of convenience without overloading. 'MMDDYY').page 12 . 'MMDDYY'). date_string := TO_CHAR (SYSDATE. ± You just probably never gave it a thought. you would have to deal with something like this: date_string := TO_CHAR_FROM_DATE (SYSDATE.Overloading in PL/SQL Built-ins  PL/SQL uses overloading in many common functions. Without overloading.

When you compile programs that use the overloaded code.  Undistinguishing characteristics: ± Functions differ only in their RETURN datatype.How Overloading Works  For two or more modules to be overloaded.  Distinguishing characteristics: ± The formal parameters of overloaded modules must differ in number. ± 2. order or datatype family (CHAR vs. ± Their formal parameters differ only in datatype and the datatypes are in the same family. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . the compiler must be able to distinguish between the two calls at compile-time. ± The programs are of different types: procedure and function. OUT. There are two different "compile times": ± 1.page 13 . IN OUT). When you compile the package or block containing the overloaded code. ± Arguments differ only in their mode (IN. VARCHAR2 is not different enough).

Examples of Invalid Overloadings PACKAGE too_similar IS PROCEDURE calc (reg_in IN CHAR). PACKAGE param_modes IS PROCEDURE proc1 (val IN VARCHAR2). which one? too_similar.func1 (v_value)). Parameter data types cause conflict. FUNCTION func1 (val IN VARCHAR2) RETURN VARCHAR2. which one? param_modes. Only difference is parameter mode.PUT_LINE (only_returns.page 14 . END only_returns. which one? DBMS_OUTPUT. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . PROCEDURE calc (reg_in IN VARCHAR2). PROCEDURE proc1 (val IN OUT VARCHAR2).calc ('123'). Only difference is function RETURN type. PACKAGE only_returns IS FUNCTION func1 (val IN VARCHAR2) RETURN DATE. END param_modes.proc1 (v_value). END too_many_cals.

you may construct different versions of the ³same´ program which correspond to different patterns of use. In this case. ± The DBMS_OUTPUT. not Value ± A less common application of overloading. so much as providing different ways of requesting the same activity.  Overloading by Type. You use the type of data and not its value to determine which of the overloaded programs should be executed.page 15 .l substitute does an even better job. the overloading does not provide a single name for different activities.Overload Wherever Possible  Supporting Many Data Combinations ± Apply the same action to different kinds or combinations of data. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  Fitting the Program to the User ± To make your code as useful as possible.PUT_LINE procedure illustrates this technique -and the PL/Vision p.

HH:MI:SS PM'). boolean_in IN BOOLEAN). PACKAGE p IS PROCEDURE l (date_in IN DATE. END p. mask_in IN VARCHAR2 := 'Month DD. YYYY . PROCEDURE l (char_in IN VARCHAR2. allowing the user to pass data to the "display engine" without writing "pre-processing" code. PROCEDURE l (char_in IN VARCHAR2.sps p. mask_in IN VARCHAR2 := µMonth DD.page 16 1/21/2011 Copyright 2001 Steven Feuerstein . number_in IN NUMBER).spb PROCEDURE l (boolean_in IN BOOLEAN). PROCEDURE l (char_in IN VARCHAR2. date_in IN DATE. PROCEDURE l (number_in IN NUMBER). PROCEDURE l (char_in IN VARCHAR2).HH:MI:SS PM'). p. PL/SQL Advanced Techniques .A "Classic" Overloaded Package  Many different datatype combinations. YYYY .

p.PUT_LINE ('TRUE').PUT_LINE ('So what is different?').l (SQLERRM.PUT_LINE (TO_CHAR (SYSDATE.PUT_LINE ('FALSE'). ELSE DBMS_OUTPUT.. SQLCODE). DBMS_OUTPUT. p. 'MM/DD/YY HH:MI:SS')).PUT_LINE (SQLERRM || ': ' || TO_CHAR (SQLCODE)). IF print_report_fl THEN DBMS_OUTPUT. END IF. 1/21/2011 Copyright 2001 Steven Feuerstein ‡Extended overloadings are more likely to meet user needs. DBMS_OUTPUT. p.page 17 . PL/SQL Advanced Techniques .l (SYSDATE). p. DBMS_OUTPUT.l ('So what is different?').Advantage of Extended Overloading ‡ Minimal overloading means lots of extra coding.l (print_report_fl)..

In my experience. If you take these different circumstances into account when you design your package specification.Fitting the Program to the User Writing "unnecessary" code? Time to overload!  A single piece of functionality. appreciated. ± If you want to write software that is admired. few developers are considerate enough of their users to try to anticipate their needs.and taken completely for granted. PL/SQL Advanced Techniques . such as "display data" or "create a file"...page 18   1/21/2011 Copyright 2001 Steven Feuerstein . ± Your code is a a more natural "fit" under a variety of requirements. the user of your package can benefit from writing less code. can be applied or needed under very different circumstances. think about the way it will be used.

 In other words. BEGIN fid := UTL_FILE. right? WRONG! PL/SQL Advanced Techniques .flg'.FOPEN ('tmp/flags'.FCLOSE (fid). even though you are simply going to close the file immediately after opening it.page 19  1/21/2011 Copyright 2001 Steven Feuerstein . you have to declare the record to hold the file handle.FILE_TYPE. UTL_FILE.Creating a File for a Quick Touch  Suppose a developer needs to create a file to be used as a "flag" in the operating system. END. Of course. ± Here is the code required by UTL_FILE: DECLARE fid UTL_FILE. ± She doesn't care what's in it. UTL_FILE. It just needs to be present. 'blah').PUT_LINE (fid. 'exists. so this is just the way it has to be. sometimes you will want to create a file and then perform additional operations. 'W').

TO_CHAR (SYSDATE)).fcreate ('exists. line_in IN VARCHAR2 := NULL) RETURN UTL_FILE. /* Function */ FUNCTION fcreate (file_in IN VARCHAR2.pkg PL/SQL Advanced Techniques . 1/21/2011 Copyright 2001 Steven Feuerstein Use as Function DECLARE fid UTL_FILE.put_line (fid.FILE_TYPE. line_in IN VARCHAR2 := NULL). Use as Procedure BEGIN PLVfile.fcreate ('temp. END PLVfile.flg').  Overloading of FCreate PACKAGE PLVfile IS /* Procedure */ PROCEDURE fcreate (file_in IN VARCHAR2. PLVfile.FILE_TYPE.ini'. v_user). END. custrules.page 20 . BEGIN fid := PLVfile.Procedure and Function Overloaded  Why not overload a "create file" program so that you can pick the one that most closely fits your situation? Consider the PLVfile package of PL/Vision.

± For example."By-Type" Overloading  In some situations. the user does not need to pass data. but the type of data. ± Pass a piece of data of the right type. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  There are three ways to accomplish this: ± Don't overload. when you use DBMS_SQL to set up a dynamic query. ± Pass a string ³name´ of the datatype.page 21 . you must call the DEFINE_COLUMN procedure to define the datatype of the Nth column in the cursor. Define a different program name for each datatype.

 Nasty hard-coding. lotsa names.page 22 . 30).DEFINE_COLUMN ± PLVgen. 30). DBMS_SQL.. DBMS_SQL.  So many program names to remember! Pass a literal value.DEFINE_INTEGER_COLUMN (cur.DEFINE_COLUMN (cur.. 2. BEGIN DBMS_SQL..DEFINE_VARCHAR2_COLUMN (cur. 1). BEGIN DBMS_SQL.Options for Specifying Column Type  Don't even bother overloading.. 2. Lotsa typing.DEFINE_COLUMN (cur. 2. DBMS_SQL.. 'NUMBER')... ± DBMS_SQL. 30)..DEFINE_COLUMN (cur. 'STRING'.  Now let's look at two examples of overloading by datatype.func 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Pass a named constant.... DBMS_SQL.DEFINE_COLUMN (cur.NUMBER_TYPE). BEGIN DBMS_SQL. 1.VARCHAR2_TYPE. DBMS_SQL.. 1.

30). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . 1.DEFINE_COLUMN (cur.Defining Dynamic SQL Columns  The DBMS_SQL.GET_TIME). 2. 30). DBMS_SQL. DBMS_SQL.DEFINE_COLUMN (cur. BEGIN DBMS_SQL. you only need to pass a value -. 2.of the correct type. v_empno). DBMS_UTILITY. from the perspective of DBMS_SQL. BEGIN DBMS_SQL. 'a'.any value -. ± The three code blocks below are equivalent. 1.DEFINE_COLUMN.DEFINE_COLUMN (cur. BEGIN DBMS_SQL.page 23 . 30). 1.DEFINE_COLUMN (cur.DEFINE_COLUMN procedure defines the datatype of a column. v_ename. ± To make it easier to accomplish this task. DBMS_SQL. USER.DEFINE_COLUMN (cur.DEFINE_COLUMN (cur. 2. 1).

please! 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . PACKAGE PLVgen IS PROCEDURE func (name_in IN VARCHAR2. type_in IN VARCHAR2).func ('last_date'. please! A number function. type_in IN DATE).Generating Functions by Value  In PLVgen. ± The particular value itself is of no importance. type_in IN NUMBER). any date.func ('total_salary'.page 24 . any string. any Boolean will do. PROCEDURE func (name_in IN VARCHAR2. 1) A date function. PROCEDURE func (name_in IN VARCHAR2. the user indicates the type of function to be generated by providing a value. Any number. SYSDATE) SQL> exec plvgen. SQL> exec plvgen.

comp_id%TYPE). END. PROCEDURE calc (comp_id_IN IN company. I rely on an anchored type (%TYPE) to establish the datatype of the second calc¶s parameter. PL/SQL Advanced Techniques .  In the above example.page 25 1/21/2011 Copyright 2001 Steven Feuerstein . PL/SQL does not sense a conflict with above overloading even though comp_id is a numeric column.The Frustrations of Overloading  Watch out! An overloading can compile successfully. but you might later found out that you cannot actually call any of the overloaded programs. PACKAGE profits IS PROCEDURE calc (comp_id_IN IN NUMBER). ± When I compile profits.

sales. sales.page 26 .  Can I overload two programs which have parameters that differ only by name. like calc_totals shown above? ± If not. why not? ± If so.pkg ? 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . how would you do it? (Don't peek at the next page!) BEGIN sales. END sales. END.calc_total ('ZONE2').calc_total ('NORTHWEST').Quiz! Nuances of Overloading PACKAGE sales IS PROCEDURE calc_total (zone_in IN VARCHAR2). PROCEDURE calc_total (reg_in IN VARCHAR2).

'.ANALYZE_OBJECT ' || '(''TABLE''. of named notation include: ± Code is more "self-documenting".estimate_percent=>50). next_date => TRUNC (SYSDATE + 1).sql  Advantages 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .''LOAD1''.page 27 . what => 'DBMS_DDL.''ESTIMATE''. ± You can skip over (not specify values for) any IN parameters that have default values. This is especially useful when working with infrequently used built-in programs. DBMS_JOB.null. namednot.submit ( job => v_jobno.Using Named Notation <formal parameter name> => <expression>  Explicit association between the formal parameter (the "name") with the actual parameter (the "value").''TENK''' || '. interval => 'TRUNC(SYSDATE+1)'). That way you don't have to know and pass default values.

Three types of collections: ± Index-by tables (Oracle7 only.Achieving PL/SQL Excellence PL/SQL Collections   Collections are single-dimensioned lists of information.page 28 . Oracle8 and above) 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . originally called PL/SQL tables) ± Nested tables (Oracle8 and above) ± Variable arrays (VARRAYs.

 Emulate bi-directional cursors.When to Use Collections  Maintain any kind of list of related information for use in your programs. Avoid mutating table errors in database triggers. Build hash tables (custom indexing structures). PL/SQL Advanced Techniques .page 29     1/21/2011 Copyright 2001 Steven Feuerstein . Improve query performance by avoiding joins. which are otherwise not supported in PL/SQL Cache data in session-level memory for faster access.

this broad range allows you to employ the row number as an intelligent key.Index-By Tables TYPE <table_type> IS TABLE OF <datatype> INDEX BY BINARY_INTEGER. Valid row numbers range: -2.page 30 . ± Available only in PL/SQL 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .147.647 » You will not actually create tables this large.  Characteristics of an index-by table: ± Unbounded » Practically speaking.483. ± Homogeneous » Data in each row has the same structure. DECLARE TYPE inmem_emp_t IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER. emp_copy inmem_emp_t.147.483.647 to 2. Instead. ± Sparse » Data does not have to be stored in consecutive rows of information.

Error: NO_DATA_FOUND 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Variable declaration children child_list_type. children (6904) := 'Lisa Nadezhka'.Index_by Tables TYPE declaration PACKAGE BODY family IS TYPE child_list_type IS TABLE OF VARCHAR2 (30) INDEX BY BINARY_INTEGER. children 6306 6412 6810 6904 µBarbara Anne¶ µGary Richard¶ µAdam Russell¶ µLisa Nadezhka¶ datemgr. Component Selection kid := children (4).pkg children 6306 6412 6904 µBarbara Anne¶ µGary Richard¶ µLisa Marie¶ children (6810) := µAdam Russell.page 31 .

Nested Tables [CREATE OR REPLACE] TYPE <table_type> IS TABLE OF <datatype> [NOT NULL]. ± Unbounded.647 ± Initially dense.  Nested table characteristics ± Homogeneous » Each row contains the same structure of data. but only with explicit EXTEND requests » Practically speaking. DECLARE TYPE when_t IS TABLE OF DATE. Valid row numbers range: 1 to 2. but can become sparse if you DELETE inner rows ± Available both in PL/SQL and SQL (as a column in a table) ± The order of elements is not preserved in the database 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 32 . birthdays when_t.147.483.

sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Nested Tables CREATE OR REPLACE TYPE child_table_type IS TABLE OF VARCHAR2 (30). CREATE TABLE db_family (surname VARCHAR2 (30). kids child_table_type) NESTED TABLE kids STORE AS kids_ntab. For ORACLE's use only db_family surname kids BOLZ BOND Eric Thomas Max Richard Barbara Anne Gary Richard Lisa Marie ntdemo.page 33 .

salaries numbers_t. ± Bounded » Upper limit established when the TYPE is defined. can be EXTENDed or TRIMmed.483.147.page 34 . ± Available both in PL/SQL and SQL (as a column in a table) » And the order of elements are preserved in the database.647 ± Dense » Never any gaps between defined rows. DECLARE TYPE numbers_t IS VARRAY (10) OF NUMBER. ± Variable arrays are actually stored in the DB table 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  Characteristics of variable arrays: ± Homogeneous » Each row contains the same structure of data. Maximum value: 2.Variable Arrays [CREATE OR REPLACE] TYPE <table_type> IS VARRAY (N) OF <datatype> [NOT NULL].

kids child_va_type). CREATE TABLE db_family (surname VARCHAR2 (30).sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Variable Arrays CREATE OR REPLACE TYPE child_va_type IS VARRAY (8) OF VARCHAR2 (30). db_family surname kids BOLZ BOND 1 Barbara Anne 2 Gary Richard 3 Lisa Marie 1 Eric Thomas 2 Max Richard vademo.page 35 .

you define the TYPE of the collection.page 36 . from the TYPE.. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Defining Collections  First. ± For index-by tables.  Then you declare an instance of that type. CREATE OR REPLACE PACKAGE tabtypes IS TYPE integer_ibt IS TABLE OF INTEGER INDEX BY BINARY_INTEGER. ± You can declare multiple collections from that TYPE. END tabtypes. Best option: package specification. this can only occur in a PL/SQL declaration section. a collection. TYPE integer_vat IS VARRAY(10) OF INTEGER. ± For nested tables and VARRAYs.. . TYPE integer_nt IS TABLE OF INTEGER. you can define the TYPE in the database with a CREATE statement. or in a PL/SQL declaration section.

± The code used to define the collection TYPE  There is no information in the data dictionary available for index-by tables.type_name IN ('NAMES_VT'.' || A.owner T. 'TMRS_VT') T.  ALL_COLL_TYPES ± The types you have created (or have access to) in the database  ALL_TYPE_ATTRS ± Attributes of the data type used in the TYPE definition.type_name.elem_type_name = A.attr_type_name Attributes all_coll_types T. all_type_attrs A T.Obtaining Collection Information SELECT FROM WHERE AND AND AND A.page 37 .sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . colldd.owner = A.owner = USER T.attr_name || ' .

it must be initialized. / DECLARE -. DECLARE TYPE numbers_t IS VARRAY (10) OF NUMBER.Initializing Collections  Before you can use a collection. 200. TYPE defined in PL/SQL TYPE defined in the database Collection used in a table PL/SQL Advanced Techniques . BEGIN CREATE TABLE employee_denorm ( employee_id INTEGER. 200. BEGIN CREATE TYPE numbers_t IS VARRAY (10) OF NUMBER.page 38 1/21/2011 Copyright 2001 Steven Feuerstein . You must initialize them explicitly with a constructor. 300). empty when declared. 300). salaries numbers_t := numbers_t (100. ± Index-by tables are initialized automatically. salaries numbers_t := numbers_t (100. ± Nested tables and VARRAYs are atomically null.Initialize the collection. salary_history numbers_t).

BEGIN comp_tab(1).comp_id := 1005. ± But you cannot have nested composite datatypes.  Starting with Oracle8. DECLARE TYPE comp_rectype IS RECORD (comp_id company. comp_tab comp_tabtype. the datatype for any of the collection types can also be an object.company_id%TYPE. Again.3. the ³homogeneous´ contents of an index-by table's row can be a record . Here we have a three step process. ± Can easily create an index-by table with the same structure as a database table by declaring a record with %ROWTYPE. total_rev NUMBER). TYPE comp_tabtype IS TABLE OF comp_rectype INDEX BY BINARY_INTEGER. consider putting TYPEs in database or packages.page 39 .Collections of Composites  Starting with Oracle 7. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

). consider using the row value as "smart data" for your application (primary key.Sparse is Nice  The sparse characteristic of index-by tables and nested tables can be put to good use. etc. ± You should not fill sequentially.  Rows do not have to be defined sequentially.  Especially handy when caching data from relational tables in user memory. ± In almost every case. ± In an index-by table. it is very similar to a database table. order by date.page 40 . a row exists in the table only when a value is assigned to that row. In this way. your collections will contain a row's worth of information. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Instead. unless the order in which items are selected is of importance.

page 41 .empno) := rec.tst  PL/SQL Advanced Techniques . CREATE OR REPLACE PACKAGE BODY psemp IS BEGIN FOR rec IN (SELECT * FROM emp) LOOP emp_tab (rec. END. Initialization section of package 1/21/2011 Copyright 2001 Steven Feuerstein  This package moves the entire contents of the emp table into its corresponding collection. emp_tab emp_tabtype. END LOOP. END. Some questions: ± Why would I put this collection table in a package? ± When is the collection loaded with the data? ± What rows in that collection are utilized? psemp.Transferring DB Table to Collection CREATE OR REPLACE PACKAGE psemp IS TYPE emp_tabtype IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER.pkg psemp.

page 42 .  For index-by tables. BEGIN greedy_ceos(1) := 'Hamilton.Collection Gotchas CREATE TYPE names_t IS TABLE OF VARCHAR2(30). once extended. ± For VARRAYs and nested tables. ± Use the EXISTS method to determine if a row existed. / DECLARE greedy_ceos names_t := names_t (). the row exists. Jordan'. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . / Error -6533! You've got to EXTEND first!  EXTEND before assigning a value to a row. even if you haven't assigned a value explicitly. END. you must reference existing rows or a NO_DATA_FOUND exception is raised. ± Not necessary for index-by tables. but you must do it for VARRAYs and nested tables.

Handling Collection Gotchas BEGIN -. optional argument. BEGIN IF salaries.Set the value of each new row to the contents of the first row.FIRST)). ± Pre-extending a large number of rows in advance can improve performance.PUT_LINE ('Data for employee not available. END IF. preextend.  You can EXTEND one or more rows.Extend by 10 since I know I will need that many.EXISTS (v_employee_id) THEN -. ± Assign a default value with a second. salaries(salaries. salaries.EXTEND (10. -.').tst  Include a handler for NO_DATA_FOUND or use the EXISTS method to avoid these exceptions.page 43 . ELSE DBMS_OUTPUT.We are OK. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

Collection Methods  Obtain information about the collection COUNT returns number of rows currently defined in the table.  The built-in package plitblm (PL/sql Index-TaBLe Methods) defines these methods. ± EXTEND adds rows to a nested table or VARRAY. ± LIMIT tells you the max. number of elements allowed in a VARRAY. EXISTS returns TRUE if the specified row is defined. ± ± ± ±  Modify the contents of the collection ± DELETE deletes one or more rows from the index-by table. ± TRIM removes rows from a VARRAY. PL/SQL Advanced Techniques .page 44 1/21/2011 Copyright 2001 Steven Feuerstein . FIRST/LAST return lowest/highest numbers of defined rows. NEXT/PRIOR return the closest defined row after/before the specified row.

Delete one (the last) row myCollection.LAST). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . 17255).DELETE (1400.Delete a range of rows myCollection.DELETE (myCollection. DELETE releases memory. -. END.DELETE.page 45 .FREE_UNUSED_USER_MEMORY. -. but you may also want to call DBMS_SESSION.Delete all rows myCollection.The DELETE Method  You can delete one or more rows from a collection using DELETE: BEGIN -.

Navigating Through Collections 


Use FIRST and NEXT to move from beginning to end. Use LAST and PRIOR to move from end to beginning.
rowind PLS_INTEGER := birthdays.FIRST; -- birthdays.LAST BEGIN LOOP EXIT WHEN rowind IS NULL; DBMS_OUTPUT.PUT_LINE (birthdays(rowind).best_present); rowind := birthdays.NEXT (rowind); -- birthdays.PRIOR END LOOP; END;

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 46

Using Collections Inside SQL 

Nested tables and VARRAYs can be defined as columns of a table and referenced directly within SQL. You can also apply SQL operations to the contents of nested tables and VARRAYs with these operators:
± THE - Maps a single column value in a single row to a virtual database table ± CAST - Maps a collection of one type to a collection of another type ± MULTISET - Maps a database table to a collection ± TABLE - Maps a collection to a database table  

Index-by tables are programmatic constructs only.
± You cannot make a direct reference to an index-by table in SQL. ± Instead, so do indirectly with a PL/SQL function.

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 47

Using Collections inside SQL
SELECT column_value FROM TABLE (SELECT children FROM db_family WHERE surname = 'BOLZ'); db_family surname children BOLZ BOND Eric Thomas Max Richard UPDATE TABLE (SELECT children FROM db_family WHERE SURNAME = 'BOLZ) SET column_value = 'Lisa Nadezhka' WHERE column_value = 'Lisa Marie'); db_family surname children BOLZ ...
1/21/2011 Copyright 2001 Steven Feuerstein
PL/SQL Advanced Techniques - page 48

Barbara Anne Gary Richard Lisa Marie

column_value Barbara Anne Gary Richard Lisa Marie

Barbara Anne Gary Richard Lisa Nadezhka

Using the THE Operator 

Use THE to manipulate (retrieve, INSERT, UPDATE, DELETE) contents of a nested table in a database table.
± Can only use with nested tables, not VARRAYs or index-by tables. ± Only accessible from within SQL statements in PL/SQL.
CREATE TYPE action_list_t IS TABLE OF VARCHAR2(100); / CREATE TABLE inflation_beater ( focus_area VARCHAR2(100), activities action_list_t) NESTED TABLE activities STORE AS activities_tab; SELECT VALUE (act) FROM THE (SELECT activities FROM inflation_beater WHERE focus_area = 'FORTUNE 100') act; UPDATE THE (SELECT activities FROM inflation_beater WHERE focus_area = 'FORTUNE 100') SET COLUMN_VALUE = 'DISBAND OSHA' WHERE COLUMN_VALUE = 'SIDESTEP OSHA';

the.sql

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 49

Using the TABLE and CAST Operators 

Use CAST to convert a collection from one type to another, TABLE to convert a TYPE into a database table.
± Cannot use with index-by tables. ± Useful when you would like to apply SQL operations against a PL/SQL collection (ie, one not stored in a database table).
DECLARE nyc_devolution cutbacks_for_taxcuts := cutbacks_for_taxcuts ('Stop rat extermination programs', 'Fire building inspectors', 'Close public hospitals'); BEGIN DBMS_OUTPUT.PUT_LINE ( 'How to Make the NYC Rich Much, Much Richer:'); FOR rec IN (SELECT COLUMN_VALUE ohmy FROM TABLE (CAST (nyc_devolution AS cutbacks_for_taxcuts))) LOOP DBMS_OUTPUT.PUT_LINE (rec.ohmy); END LOOP; cast.sql END;

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 50

species. FETCH bird_curs into bird_row. information for the BEGIN master in one trip. Retrieves all detail bird_row bird_curs%ROWTYPE. END.Using the MULTISET Operator  MULTISET is the inverse of TABLE. ± Cannot use with index-by tables. b. view.genus AND bh. converting a set of data (table.species) AS country_tab_t) FROM birds b. with potential client-server performance impact. ± You can use MULTISET to emulate or transform relational joins into collections.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .country FROM bird_habitats bh WHERE bh. multiset. query) into a VARRAY or nested table. CAST(MULTISET(SELECT bh.genus = b.species = b. OPEN bird_curs. DECLARE CURSOR bird_curs IS SELECT b.genus.page 51 .

END.Referencing IB Tables inside SQL  You can't directly reference an index-by table's contents inside SQL. WNDS). END. END. CREATE OR REPLACE PACKAGE BODY ibtab IS TYPE date_tab IS TABLE OF DATE INDEX BY BINARY_INTEGER. Make accessible in SQL for Oracle8 and below. WNPS. Instead. hiredates date_tab. call functions that retrieve the table's data. 1/21/2011 Copyright 2001 Steven Feuerstein ibtab_in_sql.page 52 . FUNCTION rowval (indx IN PLS_INTEGER) RETURN DATE IS BEGIN RETURN hiredates (indx).sql PL/SQL Advanced Techniques . but hide the index-by table structure.  CREATE OR REPLACE PACKAGE ibtab IS FUNCTION rowval (indx IN PLS_INTEGER) RETURN DATE. PRAGMA RESTRICT_REFERENCES (rowval.

page 53 .Examples of Collections in Action  Emulation of bi-directional cursor operations Avoid mutating table problems in database triggers.  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

± A talked-about feature for Oracle9i -. Notice that the collection itself is hidden.Bi-Directional Cursor Emulation  Oracle does not yet support the ability to move back and forth (and at random) through a cursor's result set.pkg bidir. This is particularly useful (read: efficient) when you need to perform multiple passes against the data. PROCEDURE prevRow.tst 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . PROCEDURE nextRow. END.nope. FUNCTION getRow RETURN employee_plus%ROWTYPE. didn't make it!  Instead. CREATE OR REPLACE PACKAGE bidir IS /* Iterate through rows in the result set */ PROCEDURE setRow (nth IN PLS_INTEGER).  bidir. deposit your data in a collection and then provide programs to access that data in the necessary fashion.page 54 .

sql  Note: in Oracle8i. it is "mutating".The Mutating Table Problem  Database triggers can be attached to the SQL statement and/or the individual row operations on a table. So what are you supposed to do when a row-level operation needs to "touch" that table? mutating. you can use autonomous transactions to relax restrictions associated with queries. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 55 . Statement Level UPDATE emp SET sal = 1000 UPDATE row 1 Row Level  UPDATE row N Row level triggers cannot query from or change the contents of the table to which it is attached.

If you are going to defer the work. 1st row trigger fires Nth row trigger fires Writes to list Writes to list Work List (PL/SQL Table)  Process data in the list. you need to defer the action until you get to the statement level. Statement Trigger 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . you have to remember what you needed to do.page 56 . ± an index-by table is an ideal repository for this reminder list.A Solution Based on Index-by Tables  Since you cannot perform the processing desired in the row-level trigger.

25 65011. we then know which departments to re-rank. ± We might update more than one department within a statement so we must be able to retain multiple department numbers.page 57 .88 144533.25 3 1 2 6 "Deferred work" is not only necessary.An Example: Ranking Salespeople  A table holds the rankings based on the amount of annual sales of salespeople within a department. Department ID Salesperson ID Sales Amount Rank 1055 1055 1055 1047  64333 65709 65706 70904 74055. the rankings must also change to show the new standings for that department only.91 109000. but preferable. ± As the sales amount is updated in this table. ± By storing the salesperson¶s department ids as they change. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

rank_depts. Statement Level Trigger CREATE OR REPLACE TRIGGER Rank_Sales_Strg AFTER INSERT OR UPDATE OR DELETE ON rank_sales BEGIN rank. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sales_amt != NEW. END.sales_amt) BEGIN rank. ranking.pkg All details of the ranking are hidden in the package body. END.page 58 .add_dept (:new.Trigger Logic Required Row Level Trigger CREATE OR REPLACE TRIGGER Rank_Sales_Rtrg AFTER insert OR update OF sales_amt ON rank_sales FOR EACH ROW WHEN (OLD. Doesn't fire unless the sales_amt is actually changed.dept_id).

dept_tab dept_tabtype. Table holds indicator that department needs re-ranking. PL/SQL Advanced Techniques . END add_dept 1/21/2011 Copyright 2001 Steven Feuerstein Create row to indicate department to be ranked. PROCEDURE add_dept (dept_id_in IN INTEGER) IS BEGIN IF NOT in_process THEN dept_tab (dept_id_in) := TRUE. END rank. PROCEDURE rank_depts. TYPE dept_tabtype IS TABLE OF BOOLEAN INDEX BY BINARY_INTEGER. END IF.page 59 . PACKAGE BODY rank IS in_process BOOLEAN := FALSE.The Ranking Package PACKAGE rank IS PROCEDURE add_dept (dept_id_in IN INTEGER).

END LOOP. v_deptid := dept_tab. END IF. perform_ranking (v_deptid).The Ranking Package. END rank. 1/21/2011 Copyright 2001 Steven Feuerstein Avoid recursive execution of logic Row number is department number.DELETE. END rank_dept. LOOP EXIT WHEN v_deptid IS NULL. in_process := FALSE. BEGIN IF NOT in_process THEN in_process := TRUE. PL/SQL Advanced Techniques . Continued PROCEDURE rank_depts IS v_deptid PLS_INTEGER := dept_tab. Clean up for next time.page 60 . dept_tab.FIRST.NEXT (v_deptid).

You want to use inside SQL. ± You want to use inside SQL. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 61 .Which Collection Type Should I Use?  Index-by tables ± Need to use in both Oracle7 and Oracle8 applications ± Want to take advantage of sparse nature for "intelligent keys". Set of data is relatively small (avoid row chaining).  VARRAYs ± ± ± ± You want to preserve the order in which elements are stored.  Nested tables ± You want to store large amounts of persistent data in a column. You don't want to have to worry about sparseness.

Tips for Using Collections 

Wrap access to your collections.
± In many cases, you will want to avoid direct access to (assigning and retrieving) rows in your collections. ± This will give you the flexibility to change your implementation. ± You can also hide complex rules for setting the row number. 

Get creative!
± Don't always fill and use the index-by table sequentially. ± If you can somehow translate your application data to an integer, it can be used as a row number, and therefore offers indexed access. ± Julian date formats and DBMS_UTILITY.GET_HASH_VALUE offer two different methods.

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 62

Achieving PL/SQL Excellence

Cursor Variables

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 63

Architecture of Cursor Variables
With Hard-Coded Cursors
Hard-Coded Cursor

With Cursor Variables

PGA

Cursor Variable

Cursor Variable

Result Set

Shared Global Area

Cursor Object

Result Set 

A cursor variable points to an underlying cursor object in the database.
± The cursor object in turns points to (and keeps its place in) a result set. 

The cursor variable can be passed between programs (even between, say, a Java servlet and a PL/SQL stored procedure).
± Static SQL only -- until Oracle8i.
PL/SQL Advanced Techniques - page 64

1/21/2011 Copyright 2001 Steven Feuerstein

Benefits of Cursor Variables 

Share cursor management between programs, even across the client-server divide.
± You don't have to pass the result sets of a cursor in order to allow the client-side program to have direct access to the data in the result set. ± Oracle Developer 2.1 utilizes cursor variables when you choose to construct a "base table block" around stored procedures instead of a database table. 

Share the same code across multiple, different queries.
± Since the cursor name is no longer hard-coded, you can use a single block of code (say, a reporting program) against different queries. ± We will try out this technique at the end of the section.

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 65

Cursor Variable Example
DECLARE TYPE company_curtype IS REF CURSOR RETURN company%ROWTYPE;
Declare a variable cursor TYPE.

company_curvar company_curtype;

Declare cursor variable based on that type. Declare a record from cursor variable. OPEN cursor variable, specifying the query. FETCH from the cursor variable.

company_rec company_curvar%ROWTYPE; BEGIN OPEN company_curvar FOR SELECT * FROM company;

FETCH company_curvar INTO company_rec;
Close the cursor variable.

CLOSE company_curvar; END;
1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 66

Explicit Cursors and Cursor Variables 

Both hard-coded cursors and cursor variables work with static SQL.
± The SQL is fixed at compile-time. ± The difference is that with cursor variables, you get to decide which static query is opened. 

Many cursor operations are the same:
± Close a variable cursor with the same syntax as that for static cursors. ± Use cursor attributes (%ISOPEN, %FOUND, %NOTFOUND, %ROWCOUNT) with cursor variables (as of Release 2.3). ± Fetch data from the cursor result set through a cursor variable with the same syntax as that of static cursors. 

Let¶s focus on the new and different capabilities of cursor variables.
PL/SQL Advanced Techniques - page 67

1/21/2011 Copyright 2001 Steven Feuerstein

Declaring Cursor Types and Variables 

Cursors are declared in two steps, just like programmerdefined records and PL/SQL tables.
± 1. Define a cursor TYPE -- either "weak" or "strong". ± 2. Define a cursor variable.
DECLARE TYPE weak_curtype IS REF CURSOR; TYPE comp_curtype IS REF CURSOR RETURN company%ROWTYPE; curcmp_new comp_curtype; cur_any weak_curtype; BEGIN
Declare cursor variables from the TYPEs. Declare a STRONG referenced cursor TYPE. Declare a WEAK referenced cursor TYPE.

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 68

Strong vs. Weak Cursor Types 

A strong (or constrained) cursor type has a defined return data specification.
± Can only reference cursor objects which return the same data specification, which can be any single SQL datatype or any previously defined record structure. ± Datatype mismatches are identified at compile time.

TYPE cur_typ_name IS REF CURSOR [ RETURN return_type ]; TYPE cur_typ_name IS REF CURSOR RETURN emp%ROWTYPE; /* Strong */ 

The weak (or unconstrained) cursor type does not have a RETURN clause.
± It can reference any cursor object, be opened FOR any query. ± Datatype mismatches can only be identified at runtime.

TYPE cur_typ_name IS REF CURSOR; /* Weak */
1/21/2011 Copyright 2001 Steven Feuerstein
PL/SQL Advanced Techniques - page 69

Opening with the Cursor Variable
OPEN cursor_name FOR select_statement; 

When you open a cursor variable (whether of the weak or strong variety), you must provide the SQL query that identifies the result set.
± If the variable has not yet been assigned to cursor object, the OPEN FOR statement implicitly creates an object for the variable. ± If the variable is already pointing to a cursor object, the OPEN FOR reuses the existing object and attaches the new query to that cursor object. 

Remember, the cursor object is nothing more than a memory location.
± It is maintained independently of the query itself.
PL/SQL Advanced Techniques - page 70

1/21/2011 Copyright 2001 Steven Feuerstein

Match Needed BEGIN OPEN emp_curvar FOR SELECT * from emp. ± You can establish the return type based on a database table.page 71 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  STRONG cursor data specifications must match or be compatible with the structure of the SELECT statement.Opening with Strong Cursor Types DECLARE TYPE emp_curtype IS REF CURSOR RETURN emp%ROWTYPE. emp_curvar emp_curtype. ... a cursor or a programmer-defined record. END.

 A weak cursor TYPE doesn't define the RETURN structure. Verification will take ELSIF get_type_in = µDEPT¶ place at the FETCH.page 72 1/21/2011 Copyright 2001 Steven Feuerstein .Opening with Weak Cursor Types PACKAGE pkg IS TYPE cv_type IS REF CURSOR. END. END IF. RETURN retval. you can associate any SELECT statement with a weak cursor variable.cv_type IS retval pkg. END. THEN OPEN retval FOR SELECT * FROM dept. BEGIN IF get_type_in = µEMP¶ THEN Either query will "do". REF TYPE placed in package so that it is "globally" available. PL/SQL Advanced Techniques . OPEN retval FOR SELECT * FROM emp. FUNCTION open_emp_or_dept (get_type_in IN VARCHAR2) RETURN pkg.cv_type.

± Fetching can continue with a different INTO clause. var_name.Fetching from the Cursor Variable FETCH cursor_var_name INTO record_name. The INTO structure must match in number and datatype to: ± FOR STRONG cursor types.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .   Compatibility checks are performed prior to fetching row.. FETCH cursor_var_name INTO var_name. ± FOR WEAK cursor types.  Fetching with cursor variables follows the same rules as those with static cursors. . ± The ROWTYPE_MISMATCH exception is raised on failure. it match the OPEN FOR statement structure.page 73 . it match the cursor type data specification.. mismatch..

± With explicit cursors.  hccursor. but static cursors are more efficient than dynamic SQL and cursor variables are less complicated than DBMS_SQL. since cursor names are "hard coded". you have to repeat the code for each cursor.When to Use Cursor Variables  Make it easier for calling programs (especially non-PL/SQL programs) to manipulate result sets. ± JDBC recognizes cursor variables.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 74 . ± You could use dynamic SQL to achieve this effect.  Define a base table block in Forms Builder (formerly Oracle Forms) on stored procedures rather than a table directly. Use a single block of code to manipulate multiple queries.

END.Consolidating Different Cursors  The following package specification hides the SQL behind a single open function. CREATE OR REPLACE PACKAGE allcurs IS bydept CONSTANT INTEGER := 1. FUNCTION open (type_in IN INTEGER) RETURN cv_t. / allcurrs. TYPE int_rt IS RECORD (key INTEGER). bysal CONSTANT INTEGER := 2.pkg allcurs.tst explcv. ± It also creates the data structures you will need to call the function.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 75 . TYPE cv_t IS REF CURSOR RETURN int_rt.

CREATE OR REPLACE PACKAGE BODY allcurs IS FUNCTION open (type_in IN INTEGER) RETURN cv_t IS retval cv_t. END. / 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 76 . ELSIF type_in = bysal THEN OPEN retval FOR SELECT empno FROM emp ORDER BY SAL. END. RETURN retval.Consolidating Different Cursors  The open function simply opens FOR a different SELECT based on the criteria passed to it. BEGIN IF type_in = bydept THEN OPEN retval FOR SELECT empno FROM emp ORDER BY deptno. END IF.

BEGIN cv := allcurs. CLOSE cv. p. change the ORDER BY clause -without having to change the code you write.open (&1). END LOOP.Hiding SQL Variations in Resulting Code  The following block demonstrates that you can alter which SQL statement to query -. v_empno emp. / 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . DECLARE cv allcurs. LOOP FETCH cv INTO v_empno.in this case. END.l (v_empno).empno%TYPE. EXIT WHEN cv%NOTFOUND.cv_t.page 77 "Report processor" is independent of the particular SELECT .

you can build screens that access data using a cursor variable-based procedural API. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .1.  Hide Variations in Underlying SQL ± You no longer have to repeat the same code for different cursors. unconstrained type.page 78 . or a more general.  Improve Client-Side Access to Data ± At least in Oracle Developer 2.Cursor Variables Let's summarize  Flexibility ± Choose which static SQL statement is executed at run-time.  Strong and Weak Types ± Create REF CURSORs for specific queries.

page 79 .Achieving PL/SQL Excellence Dynamic SQL  Dynamic SQL and dynamic PL/SQL: ± The DBMS_SQL package ± Native dynamic SQL in Oracle8i 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

1 and DBMS_SQL. What can you do with Dynamic SQL?  Build ad-hoc query and update applications. ± Construct powerful DBA utilities. ± Also supported with "native dynamic SQL" in Oracle8i.  Execute DDL inside PL/SQL programs.Dynamic SQL and PL/SQL Execution  "Dynamic SQL" mean that you construct the SQL statement or PL/SQL block at runtime and then execute it.page 80 1/21/2011 Copyright 2001 Steven Feuerstein . ± One example: implement indirect referencing in PL/SQL. PL/SQL Advanced Techniques .  Execute dynamically-constructed PL/SQL programs. ± Very common requirement on the Web. you no longer have to write SQL to generate SQL to get your job done. ± Available in PL/SQL since Release 2.

   1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Method 2: non-queries with a fixed number of host variables. Method 3: queries with a fixed number of items in the SELECT list and a fixed number of host variables. If you can recognize the types. executed a single time. you can more quickly figure out how to code your solution. Method 4: queries with a variable number of items in the SELECT list and/or non-queries with a variable number of host variables. execute one or more times.page 81 . ± NDS does not support method 4.Four Methods of Dynamic SQL   Method 1: non-queries without host variables. ± Different methods require the use of different programs in DBMS_SQL. These methods are in increasing order of complexity.

and relatively slow (performance did improve significantly as of Oracle8). DML and single row fetches. difficult to use. used for multi-row queries. ± OPEN FOR <sql string>. you would use the DBMS_SQL built-in package to execute dynamic SQL.Native Dynamic SQL  Prior to Oracle8i. used for DDL.page 82 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± But this package is very complex.  The new "native dynamic SQL" or NDS of Oracle8i offers two native statements in the PL/SQL language to implement most of your dynamic SQL requirements: ± EXECUTE IMMEDIATE <sql string>.

EXECUTE IMMEDIATE EXECUTE IMMEDIATE sql-string [INTO {define_variable[. PL/SQL Advanced Techniques . define_variables]. | record }] [USING {IN | OUT | IN OUT] bind argument [.  Use this statement to execute any dynamic SQL statement (including a PL/SQL block) except for multi-row queries..page 83   1/21/2011 Copyright 2001 Steven Feuerstein . {IN | OUT | IN OUT] bind argument]..]. including objects.. The USING clause allows you to specify bind arguments or variables to be passed into the SQL string before execution. The INTO clause allows you to pass values from the select list of a single row query into local variables.. collections and records.

USER) || '. RETURN retval.' || tab || ' WHERE ' || NVL (whr.000. '1=1') INTO retval.PUT_LINE ( 'Not the best health care system in the world. BEGIN EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || NVL (sch.sf PL/SQL Advanced Techniques . and not much of a democracy either!').page 84 . IF tabCount ('citizens'. WHERE clause.. sch IN VARCHAR2 := NULL) RETURN INTEGER IS Specify schema...sf compare with: tabcount.. 1/21/2011 Copyright 2001 Steven Feuerstein tabcount81. END. table and retval INTEGER. whr IN VARCHAR2 := NULL. 'insured = ''NO''') > 40. END IF.COUNT(*) For Any Table  Here's a handy and simple utility based on NDS: CREATE OR REPLACE FUNCTION tabCount ( tab IN VARCHAR2.000 THEN DBMS_OUTPUT.

end_in. start_in IN DATE. PROCEDURE runprog (pkg_in IN VARCHAR2. BEGIN v_str := 'BEGIN ' || pkg_in || '. col_in IN VARCHAR2. END. val_in IN NUMBER) IS BEGIN EXECUTE IMMEDIATE 'UPDATE ' || tab_in || ' SET ' || col_in || ' = :val WHERE hiredate BETWEEN :lodate AND :hidate' USING val_in. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Pass in bind variables with USING clause. CREATE OR REPLACE PROCEDURE updnumval ( tab_in IN VARCHAR2.' || name_in || '. name_in IN VARCHAR2) IS v_str VARCHAR2 (100). start_in.'. END...  Execute a stored procedure. end_in IN DATE. EXECUTE IMMEDIATE v_str.page 85 . END... EXCEPTION WHEN OTHERS THEN pl ('Compile Error "' || SQLERRM || '" on: ' || v_str).Other Execute Immediate Examples  Perform an update.

the USING clause allows me to pass an object and nested table to an INSERT statement with a variable table name.pkg PL/SQL Advanced Techniques .. ± In the following example. pers IN Person. cond. END. ± No special syntax needed.page 86 . cond IN preexisting_conditions) IS BEGIN EXECUTE IMMEDIATE 'INSERT INTO ' || tabname (hosp_name) || ' VALUES (:revenue_generator.Using Objects and Collections in NDS  One of the key advantages to NDS over DBMS_SQL is that it works with Oracle8 datatypes. PROCEDURE add_profit_source ( hosp_name IN VARCHAR2. including objects and collections. 1/21/2011 Copyright 2001 Steven Feuerstein health$. :revenue_inhibitors)' USING pers..

± Here is a simple utility the displays the values of any date. whr IN VARCHAR2 := NULL) IS TYPE cv_type IS REF CURSOR. DBMS_OUTPUT.sp END. ndsutil.pkg 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . cv cv_type. BEGIN OPEN cv FOR 'SELECT ' || col || ' FROM ' || tab || ' WHERE ' || NVL (whr.Multiple Row Queries and NDS  Oracle extends the cursor variable feature of Oracle7 to support multi-row dynamic queries. '1 = 1'). CREATE OR REPLACE PROCEDURE showcol ( tab IN VARCHAR2.PUT_LINE (val). col IN VARCHAR2. variable syntax! EXIT WHEN cv%NOTFOUND. number or string column in any table.page 87 . CLOSE cv. LOOP Familiar cursor FETCH cv INTO val. showcol. END LOOP. val VARCHAR2(32767).

column names. The USING clause for a query can only have IN bind arguments. provide a value for each distinct placeholder (by name).page 88 .pkg    1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . then you provide a value for each placeholder (by position). str2list. You cannot pass the NULL literal directly in the USING clause.Some Fine Print for NDS  You cannot pass schema elements (table names. ± If dynamic PL/SQL.) through the USING clause. ± If dynamic SQL. pass a variable with a NULL value. etc. Instead. You can have duplicate placeholders (for bind arguments).

Dynamic SQL using DBMS_SQL  Prior to Oracle8i. Supports all four methods of dynamic SQL. DBMS_SQL is a very large and complex package.     1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . You should only use DBMS_SQL when you cannot use NDS.page 89 . with many rules to follow and lots of code to write. the only way to perform dynamic SQL was with the DBMS_SQL package. in particular method 4. The overhead for using DBMS_SQL has decreased significantly in Oracle8 and again in Oracle8i.

Learning Through Examples  DDL ± Create an index from within PL/SQL  DML ± Update rows in a table  DML with binding ± Update rows using bind variables  Queries ± Method 3 and a dynamic WHERE clause  PL/SQL Version of "SELECT *" ± Example of Method 4  PL/SQL ± Create a generic calculation program 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 90 .

END.PARSE (cur.sp Creates an index on any column(s) in any table in your schema.CLOSE_CURSOR (cur).OPEN_CURSOR. tab_in IN VARCHAR2.DDL with Dynamic SQL PROCEDURE create_index (index_in IN VARCHAR2. col_in IN VARCHAR2) IS cur INTEGER := DBMS_SQL. which will be used to execute the DDL statement. DBMS_SQL. PL/SQL Advanced Techniques . fdbk INTEGER. DDL_statement. DDL_statement VARCHAR2(200) := 'CREATE INDEX ' || index_in || ' ON ' || tab_in || ' ( ' || col_in || ')'.  creind.EXECUTE (cur). ± Construct the DDL statement as a string. ± Parse and execute that DDL statement. BEGIN DBMS_SQL.page 91 1/21/2011 Copyright 2001 Steven Feuerstein . DBMS_SQL. ± Open a cursor.NATIVE). fdbk := DBMS_SQL.

CREATE OR REPLACE PROCEDURE updnumval ( col_in IN VARCHAR2. updnval1. END. DBMS_OUTPUT. BEGIN DBMS_SQL. val_in IN NUMBER) IS cur PLS_INTEGER := DBMS_SQL. DBMS_SQL.page 92 .NATIVE).ename%TYPE.PUT_LINE ('Rows updated: ' || TO_CHAR (fdbk)). fdbk PLS_INTEGER.PARSE (cur. 'UPDATE emp SET ' || col_in || ' = ' || val_in || ' WHERE ename LIKE UPPER (''' || ename_in || ''')'.sp 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . fdbk := DBMS_SQL.OPEN_CURSOR.Updates with Dynamic SQL  Update numeric column for specified employees.EXECUTE (cur).CLOSE_CURSOR (cur). DBMS_SQL. ename_in IN emp.

CREATE OR REPLACE PROCEDURE updnumval ( col_in IN VARCHAR2.CLOSE_CURSOR (cur). end_in IN DATE. fdbk := DBMS_SQL.PARSE (cur.PUT_LINE ('Rows updated: ' || TO_CHAR (fdbk)). DBMS_SQL.BIND_VARIABLE (cur.NATIVE).BIND_VARIABLE (cur.page 93 . DBMS_SQL. DBMS_SQL. 'lodate'. DBMS_SQL. start_in). END.sp updnval3. val_in IN NUMBER) IS cur PLS_INTEGER := DBMS_SQL.Updates with Bind Variables  Update salaries for date range using binding. DBMS_OUTPUT.EXECUTE (cur). 'hidate'. fdbk PLS_INTEGER. BEGIN DBMS_SQL. updnval2. end_in).OPEN_CURSOR.sp 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . 'UPDATE emp SET ' || col_in || ' = ' || val_in || ' WHERE hiredate BETWEEN :lodate AND :hidate'. start_in IN DATE.

Processing Flow for a Dynamic Query Allocate cursor memory (OPEN_CURSOR) Fill cursor with data (EXECUTE) Make sure SELECT is well formed (PARSE) Fill buffer with data (FETCH_ROWS) (EXECUTE_AND_FETCH) Bind any variables (BIND_VARIABLE) (BIND_ARRAY) Retrieve the data (COLUMN_VALUE) Give cursor structure (DEFINE_COLUMN) (DEFINE_ARRAY) Release cursor memory (CLOSE_CURSOR) 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 94 .

EXECUTE (cur).empno). fdbk := DBMS_SQL.ename). rec emp%ROWTYPE.DEFINE_COLUMN (cur.COLUMN_VALUE (cur. 1). DBMS_SQL. END.DEFINE_COLUMN (cur. CREATE OR REPLACE PROCEDURE showemps (where_in IN VARCHAR2 := NULL) IS cur INTEGER := DBMS_SQL. 2. LOOP EXIT WHEN DBMS_SQL. 2.sp showemps.COLUMN_VALUE (cur.Queries with Dynamic SQL  Show employees using a dynamic WHERE clause. 1. DBMS_SQL. ename FROM emp ' || ' WHERE ' || NVL (where_in. 'a'.empno) || '=' || rec. 60). DBMS_SQL.. 1/21/2011 Copyright 2001 Steven Feuerstein showemps. rec.sp showemp2. rec.FETCH_ROWS (cur) = 0.page 95 . DBMS_SQL.tst PL/SQL Advanced Techniques . END LOOP. BEGIN DBMS_SQL. DBMS_OUTPUT. 'SELECT empno.PUT_LINE (TO_CHAR (rec.OPEN_CURSOR.NATIVE). DBMS_SQL.. 1.CLOSE_CURSOR (cur).PARSE (cur. '1=1'). fdbk INTEGER.ename). DBMS_SQL.

nth_col. ± The resulting code is much more complicated. DBMS_SQL. nth_col. val).page 96 Very simplified pseudo-code intab. BEGIN FOR each-column-in-table LOOP add-column-to-select-list.PARSE (cur. datatype). FOR each-column-in-table LOOP DBMS_SQL.Dynamic SELECT * FROM Any Table  Method 4 example: the number of columns queried changes with each table. PL/SQL Advanced Techniques . select_string.sp 1/21/2011 Copyright 2001 Steven Feuerstein . END. END LOOP. END LOOP. DBMS_SQL. LOOP fetch-a-row. FOR each-column-in-table LOOP DBMS_SQL.NATIVE). END LOOP.COLUMN_VALUE (cur.DEFINE_COLUMN (cur. END LOOP.

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . then EXECUTE_AND_FETCH will raise the TOO_MANY_ROWS exception if more than one row is fetched by the SELECT.Using EXECUTE_AND_FETCH FUNCTION execute_and_fetch (cursor_in IN INTEGER. ± Very similar to the implicit SELECT cursor in native PL/SQL. the first row will still be fetched and available. raises NO_DATA_FOUND or raises the TOO_MANY_ROWS exception. TRUE). ± If exact_match is TRUE.page 97 . exact_match IN BOOLEAN DEFAULT FALSE) RETURN INTEGER. numrows := DBMS_SQL.  Makes it easy to execute and fetch a single row from a query. ± Even if the exception is raised.EXECUTE_AND_FETCH (cur. numrows := DBMS_SQL. which returns a single row.EXECUTE_AND_FETCH (cur).

FUNCTION dyncalc ( oper_in IN VARCHAR2. ± Using static PL/SQL. I would have to modify my screen every time a new formula was added. nargs_in IN INTEGER := arg1_in IN VARCHAR2 := arg3_in IN VARCHAR2 := arg5_in IN VARCHAR2 := arg7_in IN VARCHAR2 := arg9_in IN VARCHAR2 := ) RETURN VARCHAR2. arg8_in IN VARCHAR2 := NULL. NULL. arg4_in IN VARCHAR2 := NULL.sf dyncalc. 0. arg10_in IN VARCHAR2 := NULL dyncalc. NULL.Dynamic Formula Execution  Suppose I am building a user interface that allows a user to select a formula for execution. NULL. and enter the arguments.page 98 . ± With DBMS_SQL. arg2_in IN VARCHAR2 := NULL.pkg 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . NULL. a single function will do the trick. arg6_in IN VARCHAR2 := NULL. NULL.

DBMS_SQL. END. :salout). fdbk := DBMS_SQL. END. DBMS_SQL.even OUT arguments which are not being bound to any values. µsalout¶.More on Dynamic PL/SQL BEGIN cur := open_and_parse ('BEGIN get_max_sal (:deptin. Possibilities inherent in dynamic PL/SQL are mind-boggling! dynplsql.'). You must have a BEGIN-END around the code. v_deptin).EXECUTE (cur). Use VARIABLE_VALUE to extract a value from any variable you have bound.sql dynplsql. my_salary).BIND_VARIABLE (cur. DBMS_SQL.BIND_VARIABLE (cur. my_salary). µdeptin¶.tst    1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sp dynplsql. µsalout¶.  Use BIND_VARIABLE to bind any placeholders in the string -.VARIABLE_VALUE (cur.page 99 .

NATIVE). fdbk PLS_INTEGER. fdbk := DBMS_SQL. retval PLV. DBMS_SQL. END.page 100  dynvar.dbmaxvc2.OPEN_CURSOR. 'val'. DBMS_SQL. 'a'. RETURN retval.tst 1/21/2011 Copyright 2001 Steven Feuerstein . 'BEGIN :val := ' || nm || '. 'val'.BIND_VARIABLE (v_cur. PL/SQL does not support indirect referencing. retval).'. BEGIN DBMS_SQL. DBMS_SQL.pkg dynvar.Indirect Referencing with Dyn PL/SQL  Oracle Forms offers support for indirect referencing with the NAME_IN and COPY built-ins. DBMS_SQL.VARIABLE_VALUE (v_cur. PL/SQL Advanced Techniques .CLOSE_CURSOR (v_cur). 2000).EXECUTE (v_cur). but you can accomplish much of the same thing with dynamic PL/SQL execution. Here is an example of a "PL/SQL NAME_IN": FUNCTION valbyname (nm IN VARCHAR2) RETURN VARCHAR2 IS v_cur PLS_INTEGER := DBMS_SQL.PARSE (v_cur. END.

DBMS_SQL Status Built-ins  The package offers a set of modules to return information about the lastoperated cursor in your session.page 101 . ± Call these immediately after your usage to make sure they refer to your cursor. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  LAST_ROW_COUNT ± Returns the cumulative count of rows fetched from the cursor.  LAST_SQL_FUNCTION_CODE ± Returns SQL function code of cursor.  IS_OPEN ± Is the cursor already open?  LAST_ERROR_POSITION ± Returns relative column position in cursor of text causing error condition.  LAST_ROW_ID ± Returns the ROWID of last row processed.

Then you retrieve the column using the special COLUMN_VALUE_LONG variant.tst 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Working with LONG Values  DBMS_SQL provides special procedures so that you can extract values from a LONG column in a table.page 102 .pkg dumplong. dumplong.DEFINE_COLUMN_LONG ± DBMS_SQL. ± Transfer the LONG contents into an index-by table so that you can transfer a value of more than 32K bytes into your PL/SQL program. you define the column as a LONG.COLUMN_VALUE_LONG   First. ± DBMS_SQL.

New DBMS_SQL Features PL/SQL8 Extensions to DBMS_SQL 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 103 .

deletes and fetches. inserts.page 104 . ± Support for RETURNING clause to avoid unnecessary queries.New Features in DBMS_SQL  The functionality of DBMS_SQL has been extended in Oracle8 in several ways: ± Parse very long SQL strings ± Describe cursor columns ± Use "array processing" to perform bulk updates. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Now you can call the DBMS_SQL.DESC_TAB).page 105 .DESCRIBE_COLUMNS (c IN INTEGER. desc_t OUT DBMS_SQL.  Before PL/SQL8.DESCRIBE_COLUMNS. col_cnt OUT INTEGER.  Returns all of the column information in an index table of records. it was not possible to determine the datatypes of the columns defined in a cursor.Describing Cursor Columns PROCEDURE DBMS_SQL. ± The record TYPE is also defined in DBMS_SQL.

PUT_LINE (cols(colind).tst showcols.CLOSE_CURSOR (cur). cols).NATIVE).col_name). END LOOP. CREATE OR REPLACE PROCEDURE show_columns IS cur PLS_INTEGER := DBMS_SQL. DBMS_SQL.Basic Steps to Describe Columns  The following script shows the individual steps you will need to perform in order to use this feature. ncols PLS_INTEGER. 'SELECT hiredate. END. DBMS_SQL. empno FROM emp'. ncols.PARSE (cur. FOR colind IN 1 .DESCRIBE_COLUMNS (cur. desccols.DESC_TAB. DBMS_SQL.pkg desccols.page 106 .OPEN_CURSOR. BEGIN DBMS_SQL. cols DBMS_SQL.sp 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ncols LOOP DBMS_OUTPUT..

e. It really isn't "array processing"."Array Processing" in DBMS_SQL  PL/SQL8 now allows you to specify the use of "arrays".    This technique still. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± In actuality. DBMS_SQL is executing the specified SQL statement N times. Instead of providing a scalar value for an operation. index tables.page 107 . i. inserts. when you perform updates. DBMS_SQL then repeats your action for every row in the table. can offer a significant performance boost over Oracle7 dynamic SQL. you specify an index table.. where N is the number of rows in the table. however. deletes and fetches.

 Encapsulate statements to improve error handling.pkg whichsch. effdsql. ± Increased chance of reusing parsed SQL. ± Otherwise that SQL will be executed under the authority of the owner of the code. only possible for statements that do not need USING and INTO clauses. and easier code to write.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sql openprse.) through the USING clause.  Use the Oracle8i invoker rights model whenever you want to share your dynamic SQL programs among multiple schemas.PARSE so that you include the trace in that program. column names. ± But remember: you cannot pass schema elements (table names.page 108 . concatenate) whenever possible. ± Encapsulate DBMS_SQL. ± With NDS. though you could write variations for those as well.Recommendations for Dynamic SQL  Bind (vs. not the invoker of the code. etc.

you have upgraded to Oracle8i!  Major Advantages of NDS: ± Ease of use ± Performance ± Works with all SQL datatypes (including userdefined object and collection types) ± Fetch into records  When You'd Use DBMS_SQL: ± ± ± ± ± ± ± Method 4 Dynamic SQL DESCRIBE columns of cursor SQL statements larger than 32K RETURNING into an array Reuse of parsed SQL statements Bulk dynamic SQL Available from client-side PL/SQL 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Both implementations will still come in handy..page 109 . but DBMS_SQL is hard to use. of course.. ± If.NDS or DBMS_SQL: Which is Best?  Dynamic SQL and PL/SQL is very useful.

Achieving PL/SQL Excellence Oracle Advanced Queuing  The high performance. asynchronous. persistent messaging subsytem of Oracle 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 110 .

consistent manner.page 111 . systems are now heavily reliant on the ability of components to communicate with each other in a dependable. Distribution Center Coffee Beans Producer Shipping Service Retailer Consumer 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Who Needs Messaging? Everyone!  In the distributed world of the Internet.

Applications Relying on Messaging     Stock trading system Airline reservation system Auction portals Any e-commerce application 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 112 .

scalability and reliability all carry over to queues ± Strong history and retention ± Backup and recovery ± Comprehensive journaliing  Rich message content increases usefulness of queueing ± Use object types to define highly structured payloads  New to Oracle8i. message propagation. AQ now offers a publish/subscribe style of messaging between applications. the listen feature and notification capabilities.page 113 . ± Rule-based subscribers.Key Features of Oracle AQ  Leverage full power of SQL ± Messages are stored in database tables  Database high availability. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

page 114 .AQ architectural overview Queue Monitor process Queue table Queue ³Producers´ Enqueued messages Message 4 Message 3 Message 2 Message1 ³Consumers´ Dequeued messages Messages include both control information and ³payload´ (content) 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

AQ supports: ± ± ± ± ± Multiple queues Resetting order and priority of queued items Queue management using only SQL & PL/SQL Multiple message recipients Propagation of queue to remote servers  Oracle8i adds: ± ± ± ± Rules-based publish & subscribe Listening on multiple queues Easier monitoring Native Java interface PL/SQL Advanced Techniques .Oracle AQ Highlights  In 8.0.page 115 1/21/2011 Copyright 2001 Steven Feuerstein .

page 116 .AQ Components  The DBMS_AQ package offers enqueue and dequeue capabilities The DBMS_AQADM package provides administrative functionality to manage queues and queue tables. Underlying database tables and views The queue monitor (background process) ± Set # of processes with the AQ_TM_PROCESSES initialization parameter.    1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

DBMS_AQADM Highlights CREATE_QUEUE_TABLE DROP_QUEUE_TABLE CREATE_QUEUE DROP_QUEUE START_QUEUE STOP_QUEUE ADD_SUBSCRIBER Assigns name. assigns retry and retention properties to queue Drops a stopped queue Can also turn on/off enqueue and dequeue operations Stops queue. whether multiple consumers Drops table if all queues in the table have been stopped Associates queue table with queue.page 117 . storage clause. sort column. payload type. optionally waiting for outstanding transactions Adds an ³agent´ as a subscriber 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

text VARCHAR2(2000)).START_QUEUE (queue_name => 'msgqueue').CREATE_QUEUE_TABLE (queue_table => 'msg'. END.CREATE_QUEUE (queue_name => 'msgqueue'.pkg Start the queue PL/SQL Advanced Techniques . Define the "payload" Create the queue table DBMS_AQADM. queue_table => 'msg').page 118 . Define a queue in the queue table DBMS_AQADM.Creating Queue Tables and Queues CREATE TYPE message_type AS OBJECT (title VARCHAR2(30). 1/21/2011 Copyright 2001 Steven Feuerstein aq. queue_payload_type => 'message_type'). / BEGIN DBMS_AQADM.

but lots of complexity buried inside the parameters of these procedures.  ENQUEUE puts a message into a specified queue.The "operational package": DBMS_AQ  DBMS_AQ is deceptively simple.sql 1/21/2011 Copyright 2001 Steven Feuerstein . ± Only two procedures. and returns a RAW message handle DEQUEUE extracts a message from a specified queue Parameters control message properties such as: ± Visibility (ON_COMMIT or IMMEDIATE) ± ± ± ± Priority Delay Expiration Locking behavior PL/SQL Advanced Techniques .page 119   aq.

page 120 1/21/2011 Copyright 2001 Steven Feuerstein ..ENQUEUE_OPTIONS_T.. 'May there be many more. Declare records to hold various enqueue and msg properties. DBMS_AQ. my_msg message_type. Set up the payload with an object constructor. queueopts. aqenq*. msgid). msgprops. msgprops DBMS_AQ. my_msg.msgid_type.'). PL/SQL Advanced Techniques . BEGIN my_msg := message_type ( 'First Enqueue'.* Place the message on the specified queue and get a msg ID in return.ENQUEUE ( 'msgqueue'. msgid aq.Simple Enqueue Example DECLARE queueopts DBMS_AQ.MESSAGE_PROPERTIES_T. END.

BEFORE. Same setup as previous page . Modify the dequeue sequence by changing the deviation field and relative msg ID.. PL/SQL Advanced Techniques . 1/21/2011 Copyright 2001 Steven Feuerstein Specify a delay before the payload is available. queueopts.. my_msg := message_type ( 'Second Enqueue'.').relative_msgid := msgid1.ENQUEUE ('msgqueue'. END.sequence_deviation := DBMS_AQ..ENQUEUE ( 'msgqueue'. 'May there be many more.More Interesting Enqueue Example DECLARE .'). DBMS_AQ. queueopts. 'And this one goes first. BEGIN my_msg := message_type ( 'First Enqueue'... msgid1). queueopts.delay := 3 * 60 * 60 * 24. msgid2). msgprops.page 121 .. queueopts. my_msg. my_msg.. msgprops.. DBMS_AQ. msgprops.

REMOVE). aqdeq*.msgid_type. msgprops DBMS_AQ.* Declare records to hold various dequeue and msg properties.pkg */ my_msg message_type. msgid aq. PROCEDURE getmsg (mode_in IN INTEGER) IS BEGIN queueopts.dequeue_mode := mode_in. my_msg.Dequeue Example DECLARE queueopts DBMS_AQ.DEQUEUE ( 'msgqueue'. Dequeue operation isolated in local module.page 122 1/21/2011 Copyright 2001 Steven Feuerstein .DEQUEUE_OPTIONS_T. getmsg (DBMS_AQ. msgid). DBMS_AQ. END. getmsg (DBMS_AQ. BEGIN getmsg (DBMS_AQ. END. queueopts. Demonstrates destructive and non-destructive dequeuing.BROWSE).MESSAGE_PROPERTIES_T.REMOVE). PL/SQL Advanced Techniques . msgprops. /* defined in aq.

aqstk.Prioritized Payloads  You can assign priorities to individual payloads and then dequeue according to those priorities. BEGIN item_obj := aqstk_objtype (item). PROCEDURE push (item IN VARCHAR2) IS queueopts DBMS_AQ. msgid). g_priority := g_priority . END. msgprops.* 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . queueopts.msgid_type.pkg priority. ± The lower the numeric priority value.IMMEDIATE.  A stack implementation using AQ demonstrates this well.ENQUEUE ( c_queue.visibility := DBMS_AQ.priority := g_priority. item_obj aqstk_objtype. msgprops. msgid aq. queueopts.MESSAGE_PROPERTIES_T. the higher the priority.1.page 123 .ENQUEUE_OPTIONS_T. DBMS_AQ. msgprops DBMS_AQ.pkg aqstk2. item_obj.

multiple_consumers => TRUE).  Steps to working with a subscriber list: ± 1.AQ$_AGENT (name_in. ± The message is then not removed from the queue until all subscribers have dequeued the message. The queue table must be defined to support multiple subscribers or consumers. ± 2.CREATE_QUEUE_TABLE ( queue_table => 'major_qtable'. Add subscribers for the queue. 1/21/2011 Copyright 2001 Steven Feuerstein aqmult*. queue_payload_type => 'student_major_t'.Defining Message Subscribers  You can specify that a message is to be enqueued for a list of subscribers.* PL/SQL Advanced Techniques .ADD_SUBSCRIBER ( c_queue. NULL)).page 124 . SYS. BEGIN DBMS_AQADM. NULL. DBMS_AQADM.

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Significant enhancements in Oracle8i.  Considered by Oracle to be a core component of its overall solution. improved security.Oracle AQ . supporting a publish-subscribe model. LISTEN capability. ± Should be strongly supported "down the road".page 125 .Summary  Very powerful and flexible architecture. ± Crucial for Oracle to have a message-oriented middleware in order to offer an all-Oracle solution. ± Much more robust that DBMS_PIPE.

page 126 .Achieving PL/SQL Excellence Managing Large Objects with DBMS_LOB 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

LOB datatypes are the successor to LONGs.LOB Terms  LOB = Large OBject: a category of datatype allowing storage of ³unstructured´ data up to 4 gigabytes LOB datatype can be: ± Column in table ± Attribute in object type ± Element in nested table   Possible applications include office documents. Images.  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 127 . etc. they should no longer be used. sounds. though they will probably not be actually desupported. ± Oracle has announced deprecation of LONGs. video.

Types of Large Objects  ³Internal´ LOBs ± BLOB: unstructured binary data ± CLOB: single-byte fixedwidth character data ± NCLOB: multi-byte fixedwidth character data (or varying width in )  ³External´ LOBs ± BFILE: pointer to an operating system file  Temporary LOBs ± Internal LOBs that do not participate in transactions. improving performance.  Key programming differences: ± Internal LOBs participate in transactions.page 128 . external do not ± External LOBs are read-only from within Oracle 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

page 129 . trim ± For external LOBs: File existence test. append. erase.PL/SQL built-ins for LOBs  Package DBMS_LOB ± Supports for all LOBs: Reading. substring and instring searches. comparison and length checking ± For internal LOBs: Write. copy. close  Other built-in functions ± LOADFROMFILE (load an external BFILE into a BLOB) ± EMPTY_LOB(). open. EMPTY_CLOB() ± BFILENAME 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

page 130 .Deceptively simple example  BLOB-typed column in a table CREATE TABLE incoming_faxes (fax_id INTEGER. received DATE. END. Question: What¶s in the_fax? 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . fax BLOB). BEGIN OPEN fax_cur. CLOSE fax_cur. the_fax BLOB. FETCH fax_cur INTO the_fax.  Retrieve record with BLOB into PL/SQL variable DECLARE CURSOR fax_cur IS SELECT fax FROM incoming_faxes.

The ³LOB locator´ LOB t l sel es [ ll ] t i i t r .page 131 . tt LOBs <lob segment> fax_id 281937 received 12-JAN-98 fax <lob locator> Updati  t e LOB anges t e pointer is ompli ates se of LOBs ± LOB locators cannot span transactions ± Programs must lock records containing LOBs efore updating ± Programs performing L must accommodate dynamic LOB locator alues 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

BEGIN INSERT INTO web_pages VALUES (the_url.. 1 of 2  Must get a new LOB locator before writing into the LOB: DECLARE the_url web_pages.oodb.Example: Piecewise CLOB programmatic insert  Create a table CREATE TABLE web_pages ( url VARCHAR2(512) PRIMARY KEY.url%TYPE := 'http://www. the_loc CLOB..page 132 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .com'. htmlloc CLOB). . EMPTY_CLOB()) RETURNING htmlloc INTO the_loc.

PL/SQL Advanced Techniques . running_total PLS_INTEGER := 1.Example: Piecewise CLOB programmatic insert DECLARE the_url web_pages.url%TYPE := 'http://www. DBMS_LOB.REQUEST_PIECES(url => the_url).COUNT LOOP piece_length := LENGTH(html_tab(the_piece_no)). the_loc CLOB.. several likely exceptions offset => running_total. running_total := running_total + piece_length.html_tab. EMPTY_CLOB()) and loads a web page RETURNING htmlloc INTO the_loc.WRITE(lob_loc => the_loc. Note: We are ignoring amount => piece_length.page 133 1/21/2011 Copyright 2001 Steven Feuerstein BEGIN . FOR the_piece_no IN 1. buffer => html_tab(the_piece_no)). piece_length PLS_INTEGER. END.HTML_PIECES. This block retrieves INSERT INTO web_pages VALUES (the_url. html_tab UTL_HTTP. into a CLOB column html_tab := UTL_HTTP. END LOOP.com'.oodb.

CLOSE hcur. buffer => 'cool'). the_loc CLOB. str_offset := DBMS_LOB. amount => 4. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .com' FOR UPDATE. END. IF str_offset != 0 THEN DBMS_LOB. str_offset INTEGER.INSTR(lob_loc => the_loc.WRITE(lob_loc => the_loc.Example: Piecewise CLOB programmatic update DECLARE Program must lock the record explicitly CURSOR hcur IS SELECT htmlloc FROM web_pages WHERE url = 'http://www. offset => str_offset. pattern => 'oodb'). BEGIN OPEN hcur. FETCH hcur INTO the_loc.oodb.page 134 . END IF.

Preparing to use BFILEs  You must first create an Oracle I ORY´ ± Creates logical alias for full directory pat ± imilar to LIBRARY (used for C "external procedures").  Example: CREATE DIRECTORY web_pix AS 'D:\bill\training\pix'.page 135 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ut IRECTORY namespace is global  Syntax: CREATE OR REPLACE DIRECTORY <directory name> AS '<full path to directory>'.

. addresses Address_tab_t.. image BFILE). CREATE TYPE Business_card_t AS OBJECT ( name Name_t. phones Phone_tab_t.. CREATE TABLE web_graphics ( image_id INTEGER..  In an object type.page 136 . scanned_card_image BFILE ).Using BFILE datatype in DDL  In a table. / 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

'prodicon.  Example: DECLARE picture BFILE := BFILENAME('WEB_PIX'.page 137 . Spec: FUNCTION BFILENAME(directory_exprn.gif'). BEGIN INSERT INTO web_graphics VALUES (100015. picture).The built-in BFILENAME function  Returns value of datatype BFILE. /  Notes: ± No automatic file checking or synchronization ± No participation in transactions 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . file_exprn) RETURN BFILE. END.

DBMS_LOB. src_lob => pic_file.page 138 .FILECLOSE(pic_file). 'prodicon. / loadblob. amount => DBMS_LOB. DBMS_LOB. DBMS_LOB. END. image BLOB).gif'). DBMS_LOB.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .LOADFROMFILE(dest_lob => pic_blob_loc. DECLARE pic_file BFILE := BFILENAME('WEB_PIX'. pic_blob_loc) RETURNING image INTO pic_blob_loc.GETLENGTH(pic_file)). BEGIN INSERT INTO web_graphic_blobs VALUES (1.FILEOPEN(pic_file.FILE_READONLY). pic_blob_loc BLOB := EMPTY_BLOB().Loading File into Database BLOB CREATE TABLE web_graphic_blobs ( image_id INTEGER.

page 139 . or transaction  Ability to retrieve LOB ³chunk size´ ± Allows programmer to tune READs and WRITEs  For all internal LOBs ± OPEN & CLOSE allow control over timing. that can mean less I/O » Trigger will not fire until CLOSE » Indexes will not update until CLOSE ± ISOPEN 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . call.New DBMS_LOB APIs in 8i  Support for temporary LOBs ± No logging or rollback faster! ± Lifespan: session.

. COLD 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Complete support in PL/SQL (and other APIs) ± Much better performance and control than with LONGs ± Usable in object types HOT  Some weaknesses.page 140 .Summary  LOB support in Oracle is now significantly improved.. ± LOB locator behavior slightly abstruse ± Inability to modify BFILEs directly from within PL/SQL.Large Object .

page 141 .Achieving PL/SQL Excellence Leveraging Java Inside PL/SQL 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

. or server Not covered in this seminar  PL/SQL can call Java inside 8i server ± ± ± ± Command-line tools load Java classes DDL extensions publish Java classes Writing stored procedures. mid-tier. triggers in Java Distinct Java & PL/SQL namespaces  But first.Overview of Java interoperability  Java inside or outside 8i server can call PL/SQL ± Standard JDBC and SQLJ calls with Oracle extensions ± Same Java on client.. PL/SQL Advanced Techniques .. functions..page 142 1/21/2011 Copyright 2001 Steven Feuerstein .a BRIEF introduction to Java.

± The end of programming history as we know it? ± The easiest.Question 1: What is Java?  Could it be. slickest piece of software ever designed by human beings? ± Just the latest in a series of "silver bullets" promoted by software vendors in order to prop up quarterly sales? ± The first and only successful O-O language? ± None of the above?  We don't really need to take a vote. fastest.. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± We just need to keep a firm grip on common sense and stay focused on delivering solutions..page 143 .

± Ubiquitous in thousands of production applications and millions of lines of code. PL/SQL will still be: ± Faster and more productive than Java for database operations. ± A language in which hundreds of thousands of developers are trained. ± Supported and improved by Oracle -.page 144 . to boot.and very aggressively. it is very unlikely and totally unthinkable for years to come.Question 2: Will Java Replace PL/SQL?  While that scenario is certainly possible.  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

page 145 . ± string is definitely not the same as String. ± Well. ± Don't get overwhelmed by all the classes and all the strange quirks... you have to instantiate an object from that class.Some Important Things to Remember  Java is a case sensitive language.. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  Everything is a class (or an object instantiated from a class).. ± Before you can call a (non-static) class method..  You don't have to know how to do everything with Java to get lots of value out of it. everything exception the primitive datatypes..

except the "special" main method.. Oh. CREATE OR REPLACE PROCEDURE hello IS BEGIN DBMS_OUTPUT.println ("Hello world!").. public class Hello { public static void main (String[] args) { System.Building a Java Class  Let's start from the very beginning.PUT_LINE ('Hello world!'). ± Used to test or run stand-alone a class.out. END.page 146 . by the way: the PL/SQL version 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . } }  No members. no methods.

java file to a .d:\java D:> javac Hello. ± It will also automatically recompile any classes used by your class that has not been compiled since last change.page 147 . ± This will convert the .zip.java -classpath d:\java 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Compiling Classes  Before you can use a class. you must compile it with the javac command. SET CLASSPATH = d:\Oracle\Ora81\jdbc\lib\classes111.7b\lib\classes.class file. e:\jdk1.zip.1. ± You must also either have set the CLASSPATH or include it in your javac call.

java 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Running a Class  Run a class? What does that mean? It means that if your class contains a method with this header: public static void main (String[] args)  then you can "run" the main method with the java command: d:\java> java Hello  You can also pass one or more arguments on the command line: d:\java> java Hello mom Hello2.page 148 .

you will use a class by instantiating objects from the class and then invoking class methods on the object.   1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . however.Using a Class  The main method is handy for providing a built-in test mechanism of your class.page 149 . Usually. Let's build a performance analyzer class to explore these ideas.

} public void showElapsed () { p. } } p. class Tmr { private long Gstart = 0.java InFile. } public long elapsed () { return (System.currentTimeMillis() . public void capture () { Gstart = System.currentTimeMillis(). System. } public void showElapsed (String context) { p.java Tmr.l ("Elapsed time for " + context.Compare Performance of Methods  Use System.l ("Elapsed time ".currentTimeMillis to calculate elapsed time to nearest thousandth of a second.Gstart).Gstart).java 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . elapsed()).page 150 .currentTimeMillis() .

 Interface class ± The class only contains unimplemented methods.  Abstract class ± The class can contain members and methods. besides the "regular" kind we just saw..Types of Classes  There are several different kinds of classes in Java. but at least one method remains unimplemented.page 151 ..  Inner class ± Classes that are defined inside other classes. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

java A Class Hierarchy Management NonManagement Corporation 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Dynamic polymorphism: form is determined at run-time. supertype/"wider" Citizen Person Employee Hourly Worker Salaried Worker subtype/"narrower" War Criminal Person. either as its own class or as any superclass.page 152 .  Polymorphism ± An object of a class can have "multiple" forms. ± Static polymorphism: form is chosen at compile-time (PL/SQL overloading).And Now for Some Scary Buzzwords!  Inheritance ± Subclasses inherit methods and variables from extended superclasses.

myName = "Feuerstein". myName = "Steven". if (myName. if you assign a new value to it.Language Basics  Comments // Single line comment /* Block comment */ /** Documentation comment */  Primitive datatypes ± So I lied. String myName.equals(YourName)) foundFamily(). these are not objects instantiated from classes. boolean char byte short int long float double  Strings ± A String object is a read-only.page 153 . ± Can't do a direct == comparison. you are actually allocating a new object. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

length.Writing Loops in Java  Three kinds of loops: while. do-while and for ± Note: you need squiggly brackets only if there is more than one statement in the loop body. indx < args.NextElement()).out.println ( (String)enum.println (args[indx]). step) { lotsaStuff } while (expression) { lostsaStuff } do { lostsaStuff } while (expression).page 154 . static void processAll (Enumeration enum) { while (enum. indx++) System.out. for (initialize.nextElement()) } } 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .hasMoreElements ()) { processIt (enum. Examples: for (indx indx=0. System. expression.

public PuterLingo (String name) { mname = name. ± No default values for arguments. } } 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . you still include the open and close parentheses. you must supply a value for each parameter.name()). ± If a method has no arguments. } public String name () { return mname.out..println (Java. ± Only positional notation is supported. } } class LotsALingos { public static void main (String args[]) { PuterLingo Java = new PuterLingo("Java"). class PuterLingo { private String mname.Passing Parameters  Some important differences from PL/SQL.page 155 .. System.

println (e. Put inside try clause File myFile = new File (filename). "WHEN OTHERS" } in Java } 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . } catch (Exception e) { System. return myFile.length().out.equals("")) throw new Exception ("Filename is NULL"). rather than raise and handle. you "throw" and "catch" exceptions. Throwing my own public static int numBytes (String filename) { exception try { if (filename.page 156 .toString()). } File-related catch (SecurityException e) { exceptions return -1.Exception Handling in Java  Very similar to PL/SQL.

NoSuchFile { . } 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques ...Differences Between Java & PL/SQL  Exceptions are objects derived directly or indirectly from the Exception class.page 157 . ± Use the throws clause in your specification. as in: public static int numBytes (String filename) throws SecurityException.  You must inform users of your method of which exceptions may be thrown. ± So you can pass them as arguments and do anything and everything else you can do with objects.

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 158 .Java's Not So Tough!  You can learn enough Java in less than a week to: ± Build simple classes ± Leverage Java inside PL/SQL  Moving to the next level of expertise will be more of a challenge. ± Object oriented development (Java) is very different from procedural coding (PL/SQL).  Now let's explore how you can put Java to work for you inside PL/SQL programs.

Java Stored Procedures (JSPs) Java applet or app.page 159 . using JDBC or SQLJ Oracle 8i server PL/SQL cover for Java method Java virtual machine running Java method Oracle Developer client (PL/SQL) Net8 OCI or Pro*C client VB or C++ via OO4O or ODBC 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

better file I/O ± RMI callouts.JSPs: Some sample uses PL/SQL extender ± For example. network communication in/out PL/SQL replacement ± More standard language ± Good performer for numeric processing tasks ± Beware database I/O & string manipulation performance Scaleable deployment of third party code ± Vertical application ± Web server ± XML parser/generator 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 160 .

END 4.page 161 . Call from PL/SQL (or SQL) as if calling PL/SQL    1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques ... rather than BEGIN. Create Java classes in your favorite IDE 2.Creating JSP to call from PL/SQL   1. Load into server using ³loadjava´ command-line tool 3. Grant privileges as desired 5. Publish PL/SQL cover using AS LANGUAGE JAVA...

out. CEOCompensation = PceoComp.Create Java class(es) class Corporation extends Person { long layoffs. long Playoffs.out. paying its" + " Chief Executive Officer " + CEOCompensation. public Corporation ( String Pname. long CEOCompensation.println (TheGlobalMonster).println main method is used to test the class. } public static void main (String[] args) { // A very scary company Corporation TheGlobalMonster = new Corporation ( "Northrup-Ford-Mattel-Yahoo-ATT". 5000000. 50000000). layoffs = Playoffs. Entry points must be public static in most cases Classes may call other classes Avoid GUI calls     person. System.java Advanced Techniques . }} 1/21/2011 Copyright 2001 Steven Feuerstein Notes on Java classes  toString method automatically used by System.page 162 PL/SQL . long PceoComp) { name = Pname. } public String toString () { return name + " is a transnational entity with " + layoffs + " laid-off employees.

jar file Oracle 8i server Java class Java source Java resource loadjava Example: loadjava loadjava -user scott/tiger -oci8 -resolve datacraft/bill/Hello.class file .page 163 .Upload using ³loadjava´ utility .java file Java resource file .class options (abbreviated) -oci8 -resolve loadjava will connect using OCI driver Resolves external class references at compile time -resolver (shown later) Search path like CLASSPATH 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

String'..page 164 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .) [ return <Ja a t pe fullname> ]'.. /  Syntax (simplified) CREATE [ OR REPLACE PROCE URE FUNCTION <name> <sqlt pe> ] [ [ <ar s> ) ] [ AUTHID { DEFINER | CURRENT_USER } ] AS LANGUAGE JAVA NAME '<met fullname> (<Ja a t pe fullname>.lang.Publish  Example (top-level call spec) CREATE OR REPLACE FUNCTION hello_emp (empno_in IN NUMBER) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'datacraft. .bill.Hello.Emp(int) return java.

PRINT :thename ± CALL avoids overhead of SELECT fn FROM DUAL jsp.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 165 .PUT_LINE(hello_emp(7499)). END.Call the wrapped method  Method 1: Call as if PL/SQL module BEGIN DBMS_OUTPUT.  Method 2: Use 8i SQL CALL statement. from SQL*Plus: VARIABLE thename VARCHAR2(12) CALL hello_emp(7499) INTO :thename. for example.

BigDecimal oracle.sql.Timestamp java.more concepts Shape mapping ± Java methods declared ³void´ become PL/SQL procedures ± Signature mismatches detected only at runtime Type mapping (typical) VARCHAR2 DATE NUMBER user-defined object type user-defined object type object REFerence user-defined collection type java.ARRAY 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .STRUCT <named type> oracle.Publishing -.sql.page 166 .lang.sql.REF oracle.math.sql.String java.

/ (No package body required in this case) 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Publish in PL/SQL Package Spec  Designate Java module in PL/SQL package spec..Emp(int) return java.page 167 . CREATE OR REPLACE PACKAGE hello_pkg AS FUNCTION hi_emp (empno_in IN NUMBER) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'datacraft. END.lang..Hello.String'.util.

/ CREATE OR REPLACE PACKAGE BODY hello_pkg2 AS FUNCTION hi_emp (empno_in IN NUMBER) RETURN VARCHAR2 IS LANGUAGE JAVA NAME 'datacraft. END.util.lang..Emp(int) return java..page 168 .Publish as module in package body  .Hello.String'. / 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .or in package body CREATE OR REPLACE PACKAGE hello_pkg2 AS FUNCTION hi_emp (empno_in IN NUMBER) RETURN VARCHAR2. END.

page 169 .Emp(int) return java.Publish as object type method  Either in spec: CREATE OR REPLACE TYPE foo_t AS OBJECT ( bar VARCHAR2(30).Emp(int) return java.Hello.lang. MEMBER FUNCTION hello_emp RETURN VARCHAR2 IS LANGUAGE JAVA NAME 'datacraft. / or in the body: CREATE OR REPLACE TYPE foo_t AS OBJECT ( bar VARCHAR2(30). / 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .String'). END.util. MEMBER FUNCTION hello_emp RETURN VARCHAR2). / CREATE OR REPLACE TYPE BODY foo_t AS MEMBER FUNCTION hello_emp RETURN VARCHAR2 IS LANGUAGE JAVA NAME 'datacraft.Hello.String'.util.lang.

page 170 . or resource ± Can read file designated with BFILE() function  ALTER JAVA: compiles Java source. JAVA_ADMIN. resolves Java class references. DROP JAVA: drops a named Java library unit Several roles available for Java operations: ± JAVAUSERPRIV.   1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . JAVAIDPRIV. JAVASYSPRIV (needed for file IO operations).New DDL Statements and Roles  CREATE JAVA ± Alternative to ³loadjava´ utility ± Creates or replaces an Oracle ³library unit´ from Java source. JAVADEBUGPRIV ± You can also grant specific privileges. class.

jdbc2.sql.SQLData 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Passing Oracle8 objects Oracle8i server Object in O-R table Java application Java object   Harder than you¶d think Three different interfacing techniques ± oracle.STRUCT ± oracle.page 171 .sql.CustomDatum ± oracle.

page 172 .JPublisher utility Database server Definition of type or REF in data dictionary User-supplied JPublisher input file What does it do? ± Generates Java that encapsulates type and REF types of mapping supported for methods JPublisher ± ³Oracle mapping´ ± ³JDBC mapping´ ± ³Object JDBC mapping´ Three Generated Java file(s) for use in Java programs 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

AccountRuntime.Account_t)'. /  jspobj.save (datacraft.bill.Passing object using JPub-generated Java  After generating and uploading classes with JPub.page 173 .sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .bill. they become available to use in mapping Example of passing an Account_t object: CREATE OR REPLACE PROCEDURE account_save (new_acct IN Account_t) IS LANGUAGE JAVA NAME 'datacraft.

  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Example: Improving File I/O  You can read/write files in PL/SQL with UTL_FILE. Let's see how we can make that great Java stuff available from within PL/SQL. but that package is very limited. Java offers many file-related classes with much greater capabilities.page 174 .

Encapsulate Java Classes  You won't generally access native Java methods in your PL/SQL wrapper.  Let's start with something simple. ± The File class offers a length method that returns the number of bytes in a file.. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques ..page 175 . ± Instead build a static method that instantiates a Java object from the class and then invokes the relevant method against that object. ± This is not available through UTL_FILE (though you can get it through DBMS_LOB).

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .io. public class JFile2 { public static long length (String fileName) { File myFile = new File (fileName). ± Instantiate a File object for the specified name.File.length().My Own Java Class for File Manipulation  Accept the name of a file and return its length.page 176 . } } JFile2.java  Take each of these steps: ± Import the File class to resolve reference. ± Call the method of choice against that object and return the value. return myFile. import java.

page 177 .Build a Package over Java Method  Let's put it in a package.pkg 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . / CREATE OR REPLACE PACKAGE BODY xfile IS FUNCTION length (file IN VARCHAR2) RETURN NUMBER AS LANGUAGE JAVA NAME 'JFile.lang.length (java. we will certainly want to add more functionality over time. END. END.String) return long'. ± I translate the Java long to a PL/SQL NUMBER. CREATE OR REPLACE PACKAGE xfile IS FUNCTION length (file IN VARCHAR2) RETURN NUMBER. / xfile2.

Convert the Java boolean to a String or number and return that value. you will need to take these steps: ± 1. Write a "public" PL/SQL wrapper function to convert that number to a true PL/SQL Boolean. ± 3. Not so! To pass a Boolean back from Java to PL/SQL. Write a "hidden" PL/SQL wrapper function that returns the string or number. so you'd expect smooth sailing.  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 178 . ± 2.Mapping the Boolean Datatype  Both Java and PL/SQL support a native Boolean datatype.

io.java  Translate TRUE to 1 and FALSE to 0.File.canRead(). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . boolean retval = myFile.page 179 . not a Boolean class. public class JFile3 { public static int canRead (String fileName) { File myFile = new File (fileName). } } JFile3. import java. ± And don't forget: this is a boolean primitive. else return 0. if (retval) return 1.Translate Boolean to Number  Accept the name of a file and return its length.

Wrapper for Pseudo-Boolean function  Simple translation back to PL/SQL Boolean.String) return int'.java / xfile.page 180 . / CREATE OR REPLACE PACKAGE BODY xfile IS FUNCTION IcanRead (file IN VARCHAR2) RETURN NUMBER AS LANGUAGE JAVA NAME 'JFile3. END. CREATE OR REPLACE PACKAGE xfile IS FUNCTION canRead (file IN VARCHAR2) RETURN BOOLEAN. FUNCTION canRead (file IN VARCHAR2) RETURN BOOLEAN AS BEGIN xfile3..pkg 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .java END. JFile4..lang.pkg END.pkg RETURN IcanRead (file) = 1. JFile.canRead (java. xfile4. ± Avoid the hard-codings with named constants.

tst PL/SQL Advanced Techniques . } } Extract individual attribute values from the array. // starting with 0 String laborType = (String)(attribs[0]).out. Object[] attribs = e.println ( "Pay " + laborType + " $" + hourly_rate + " per hour").java passobj. // Access individual attributes by array index. System.Passing Objects to Java with STRUCT  You can pass Oracle object information to Java without relying on JPub by using the STRUCT class.sql.page 181 . 1/21/2011 Copyright 2001 Steven Feuerstein UnionBuster. BigDecimal hourly_rate = (BigDecimal)(attribs[1]). public class UnionBuster { Obtain attributes of public static void wageStrategy (STRUCT e) the Oracle object. throws java.SQLException { // Get the attributes of the labor_source object.getAttributes().

'5')). / CREATE OR REPLACE PROCEDURE bust_em_with ( labor_source_in IN labor_source_t) AS LANGUAGE JAVA NAME 'UnionBuster.wageStrategy (oracle.page 182 . / BEGIN bust_em_with ( labor_source ('Workfare'. END. 1/21/2011 Copyright 2001 Steven Feuerstein Fully specify the STRUCT class in parameter list. hourly_rate NUMBER).STRUCT)'. 0)). The Oracle object type definition CREATE TYPE labor_source_t AS OBJECT ( labor_type VARCHAR2(30). bust_em_with ( labor_source ('Prisoners'. PL/SQL Advanced Techniques .sql.Wrapping a STRUCT-based Method  You can pass Oracle object information to Java without relying on JPub by using the STRUCT class.

± Here is a good nucleus for a login. public class HelloAll { public static void lotsaText ( int count) { for (int i = 0.PUT_LINE: System.sql file: SET SERVEROUTPUT ON SIZE 1000000 CALL DBMS_JAVA.tst 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .SET_OUTPUT (1000000).out. ± Call it within methods and output will display in your Java environment. }}}  When called within a PL/SQL wrapper.println ( "Hello Hello Hello Hello Hello All!").out.page 183 . you can redirect the output to the DBMS_OUTPUT buffer. HelloAll. i < count. i++) { System.println.java HelloAll.Viewing Output from Java Methods  Java provides a "print line" method similar to DBMS_OUTPUT.

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . you "throw" and "catch". getErrorCode() and getMessage() to obtain information about the error thrown.Error Handling with Java-PL/SQL  Java offers a very similar. ± Exceptions are objects instantiated from the Exception class or a subclass of it.SQLException. ± Use two methods.1. but more robust error handling mechanism than PL/SQL. ± Instead of raising and handling.page 184 . such as java.sql. ± And also spew out the entire Java error stack! (at least through 8.5).  Any error not caught by the JVM (Java virtual machine) will be thrown back to the PL/SQL block or SQL statement.

java) at oracle.jdbc.OracleStatement.kprb.sql.Trapping and Identifying Errors  Currently.SQLException: ORA-00942: table or view does not exist at oracle.object(DropAny.check_error(KprbDBAccess. the entire Java stack is displayed on your screen. EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT. and you have to do some digging to extract the Oracle error information.jdbc.jdbc.doExecuteWithTimeout(OracleStatement.KprbDBAccess.OracleStatement.kprb.java) at DropAny.sql.page 185 .jdbc.doExecuteWithBatch(OracleStatement.parseExecuteFetch(KprbDBAccess. / SQL> 2 3 4 5 6 7 8 9 java.tst ORA-00942: table or view does not exist 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .java) at oracle.sp dropany2.java) at oracle.OracleStatement.SQLException: getErrInfo. BEGIN dropany ('TABLE'. 'blip').java) at oracle.OracleStatement.doExecuteOther(OracleStatement.driver. END.driver.doExecute(OracleStatement.executeUpdate(OracleStatement.driver.jdbc. DBMS_OUTPUT.java) at oracle.jdbc.java -29532 dropany.OracleStatement.java:14) DropAny.jdbc.KprbDBAccess.java) at oracle.driver.driver.PUT_LINE (SQLCODE).tst ORA-29532: Java call terminated by uncaught Java exception: java.PUT_LINE (SQLERRM).

page 186 .  An Oracle8 feature that allowed relatively "native" callouts to C from PL/SQL for the first time. or method. ± Must be a shared object library on Unix or a dynamically linked library (DLL) on Windows. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . procedure.Achieving PL/SQL Excellence External Procedures  An external procedure is a 3GL routine that can serve as the ³body´ of a PL/SQL function.

Process & data flow Application Makes request Net8 External Procedure Listener spawns External Shared Library Calls PL/SQL Runtime Engine PL/SQL body Client or server-side application returns results calls routine from Routine in .page 187 .so file extproc returns results returns results 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .DLL or .

External procedures: Sample uses      Send email Invoke operating system command Invoke custom or legacy application Call C runtime library function Perform admin tasks email.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sql diskspace.page 188 .

dll'.dll ± For given drive letter. create an Oracle8 ³library´: CREATE OR REPLACE LIBRARY nt_kernel AS 'c:\winnt\system32\kernel32. / 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 189 . this function returns: » » » » » sectors per cluster bytes per sector number of free clusters total number of clusters ³return code´ indicating success or failure  First.Determine free disk space on NT (1/4)  Use pre-existing routine: ± GetDiskFreeSpaceA in kernel32.

total_number_of_clusters OUT PLS_INTEGER) RETURN PLS_INTEGER. number_of_free_clusters OUT PLS_INTEGER. END disk_util. sectors_per_cluster OUT PLS_INTEGER.Package spec (2/4)  Nothing unexpected here: CREATE OR REPLACE PACKAGE disk_util AS FUNCTION get_disk_free_space (root_path IN VARCHAR2.page 190 . / 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . bytes_per_sector OUT PLS_INTEGER.

END disk_util. RETURN LONG).0 (3/4) CREATE OR REPLACE PACKAGE BODY disk_util AS FUNCTION get_disk_free_space (root_path IN VARCHAR2. number_of_free_clusters BY REFERENCE LONG.page 191  All the magic is in the EXTERNAL section 1/21/2011 Copyright 2001 Steven Feuerstein . number_of_free_clusters OUT pls_integer. bytes_per_sector OUT PLS_INTEGER. PL/SQL Advanced Techniques . total_number_of_clusters OUT PLS_INTEGER) RETURN PLS_INTEGER IS EXTERNAL LIBRARY nt_kernel NAME "GetDiskFreeSpaceA" LANGUAGE C CALLING STANDARD PASCAL PARAMETERS (root_path STRING. total_number_of_clusters BY REFERENCE LONG. sectors_per_cluster OUT PLS_INTEGER. sectors_per_cluster BY REFERENCE LONG. bytes_per_sector BY REFERENCE LONG.Package body in Oracle 8.

Usage (4/4)
DECLARE lroot_path VARCHAR2(3) := 'C:\'; lsectors_per_cluster PLS_INTEGER; lbytes_per_sector PLS_INTEGER; lnumber_of_free_clusters PLS_INTEGER; ltotal_number_of_clusters PLS_INTEGER; return_code PLS_INTEGER; free_meg REAL; BEGIN return_code := disk_util.get_disk_free_space (lroot_path, lsectors_per_cluster, lbytes_per_sector, lnumber_of_free_clusters, ltotal_number_of_clusters); free_meg := lsectors_per_cluster * lbytes_per_sector * lnumber_of_free_clusters / 1024 / 1024; DBMS_OUTPUT.PUT_LINE('free disk space, Mb = ' || free_meg); diskspace.sql END;
1/21/2011 Copyright 2001 Steven Feuerstein
PL/SQL Advanced Techniques - page 192

Creating your own external procedure 

1. Identify or create shared library 2. Identify or CREATE LIBRARY within Oracle 3. Map the parameters using:
± EXTERNAL clause (Oracle8) or ± LANGUAGE clause (Oracle8i)  

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 193

1. Identify/create external routine 


Prerequisite: O/S must support shared libraries Some useful routines are pre-built in C runtime library
± On Unix: /lib/libc.so ± On NT: <systemroot>\system32\crtdll.dll 

Building a shared library of your own requires knowledge of:
± Appropriate language (typically C) ± Compiler & linker

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 194

2. Create the Oracle library 

Syntax:
CREATE OR REPLACE LIBRARY <library name> AS '<full path to file>'; 

Assigns a programmer-defined alias to a specific shared library file Notes
± Requires CREATE LIBRARY pri ilege ± Does not alidate directory ± Can¶t use symbolic link 

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 195

3. Map the parameters
This can get complicated, because«
± Must pass extra parameters to designate:
» NULL/NOT NULL state » String length » Maximum allocated length

± Six choices of parameter mode
» » » » » » IN RETURN IN BY REFERENCE RETURN BY REFERENCE OUT IN OUT

These details are better suited for close reading«
PL/SQL Advanced Techniques - page 196

1/21/2011 Copyright 2001 Steven Feuerstein

page 197 .Achieving PL/SQL Excellence Oracle8i New Features Autonomous Transactions Invoker Rights Model Row Level Security 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

Oracle8i New Features  Oracle8i offers a number of PL/SQL-specific features that give you tremendous additional flexibility and capability.page 198 . ± And the learning curve to take advantage of these features is generally not too steep.    Autonomous Transactions The Invoker Rights Model Row level security 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

 With Oracle8i. a COMMIT or ROLLBACK in any program in your session committed or rolled back all changes in your session. you can now define a PL/SQL block to execute as an "autonomous transaction".Autonomous Transactions  Prior to Oracle8i. ± There was only one transaction allowed per connection. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 199 . msg IN VARCHAR2) AS PRAGMA AUTONOMOUS_TRANSACTION. CREATE OR REPLACE PROCEDURE loginfo ( code IN PLS_INTEGER. ± Any changes made within that block can be saved or reversed without affecting the outer or main transaction.

PL/SQL Advanced Techniques .  Call functions within SQL that change the database. software usage meter. ± Now you can avoid the complexities (need for ROLLBACK TO savepoints and so on). which can cause all sorts of complications: your log entry becomes a part of your transaction.page 200 1/21/2011 Copyright 2001 Steven Feuerstein .When to Use Autonomous Transactions  Reusable Application Components ± ATs are more or less required in the new distributed application architecture of the Internet.  Tracing Code Usage ± Build retry mechanisms.  Logging Mechanism ± Commonly developers lot to database tables. etc. something like a COMMIT) on other components. ± One component should not have any impact (esp.

pkg log81*. logger. BEGIN INSERT INTO logtab VALUES (code_in.program ). text_in IN VARCHAR2 ) IS PRAGMA AUTONOMOUS_TRANSACTION. rec. END.Logging with ATs  Don't forget that ROLLBACK in the exception section! CREATE OR REPLACE PACKAGE BODY log IS PROCEDURE putline ( code_in IN INTEGER. EXCEPTION WHEN OTHERS THEN ROLLBACK.page 201 . END.pkg retry. 1/21/2011 Copyright 2001 Steven Feuerstein Avoid interdependencies with the main transaction. rec. USER. text_in. COMMIT.tst PL/SQL Advanced Techniques . SYSDATE.machine. USER.sp log81.tst retry. While we're at it. SYSDATE. let's add some session information.

± Place the SET TRANSACTION statement in the outer transaction.  Any changes committed in an AT are visible in the outer transaction. ± You cannot define an entire package as an AT.   The AT PRAGMA goes in the body of packages. or an error is raised. ± You can use the SET TRANSACTION ISOLATION LEVEL SERIALIZABLE to indicate that you do not want the changes visible until the outer transaction commits. The AT PRAGMA can be used only with individual programs and toplevel anonymous blocks.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . autonserial. ± You cannot define a nested anonymous block to be an AT.page 202 .sql auton_in_sql.sql autontrigger*. ± You cannot tell by looking at the package spec if you are calling ATs or not -and this info is not available in the data dictionary.Tips and Gotchas with ATs  An AT program must COMMIT or ROLLBACK before terminating.

whenever you executed a stored program.page 203 1/21/2011 Copyright 2001 Steven Feuerstein . it ran under the privileges of the account in which the program was defined. ± This is called the « Definer Rights Model  With Oracle8i. ± This is called the « Invoker Rights Model PL/SQL Advanced Techniques .The Invoker Rights Model  Prior to Oracle8i. you can now decide at compilation time whether your program or package will execute in the definer's schema (the default) or the schema of the invoker of the code.

page 204 . Note: Oracle built-in packages have long had the capability of running under the invoker's authority. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .About Definer Rights  Allows you to centralize access to and control of underlying data structures. But it can be a source of confusion and architectural problems. Ignores roles and relies on directly-granted privileges. OE Code Order_Mgt Place Cancel Sam_Sales Close Old Orders  OE Data X  Orders Cannot alter table directly.

unless you write code in the package to essentially recreate roles programmatically.page 205 ..it's all or nothing.Problems with Definer Rights  Deployment & maintenance ± Must install module in all remote databases where needed ± In some databases. each user has own copy of table(s)..and now you do! 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Can bypass 8i¶s ³fine-grained´ access features (see the DBMS_RLS package) ± Difficult to audit privileges  Sure would be nice to have a choice. requiring copy of stored module  Security ± No declarative way to restrict privileges on certain modules in a package -.

the objects referenced may well be different from those against which it compiled.. and must be at the package level. Synonyms may be necessary if modules use object names not qualified by schema.  For modules with separate spec and body. You could also create local.Oracle8i Invoker Rights Syntax  For top level modules: CREATE [ OR REPLACE ] <module type> [ AUTHID { DEFINER | CURRENT_USER } ] AS .. ± At run-time. AUTHID goes only in spec.page 206 . ± In other words.  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . "dummy" objects. do what it takes to get the code to compile.

..). Central Code schema PACKAGE acct_mgr make AUTHID CURRENT_USER User/Data schema PROCEDURE mng_account IS BEGIN . accounts table 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .destroy(.. modify destroy ... you can execute code owned by another schema..acct_mgr.FROM accounts WHERE. yet have all references to data structures "reflect back" into your own schema."Reflection" Capability of Invoker Rights  With invoker rights. END..page 207 .. code.

the definer rights model is always applied to resolve the reference. taking advantage of the invoker rights model whenever possible? ± A creative use of SQL*Plus substitution variables comes in very invdefinv. all other calls in stack are resolved according to definer rights. ± Both static and dynamic SQL is supported.  Information about the rights model is not available in the data dictionary What if you want to maintain a single version of your code for both pre-Oracle8i and Oracle8i installations.sql handy.Tips and Gotchas for Invoker Rights  Does not apply to code objects.page 208 .sql  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± AUTHID CURRENT_USER is ignored. only data ± When your stored code references another stored code element. Note: cannot use with wrapped code. oneversion.  Once a definer rights program is called.

authid. but you want their own directly-granted privileges to determine access.page 209 . National HQ Check City Statistics New York Schema stolenlives Chicago Schema stolenlives  Especially handy with dynamic SQL.When to Invoke Invoker Rights  You want to reuse the same code among many users. ± Share a program that uses dynamic SQL (whether DBMS_SQL or the new native implementation) and you end up taking the most unexpected DDL and DML detours.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sql whichsch*.

Combining Invoker & Definer Rights  Rely on invoker rights to allow centralized code to work with schema-specific data.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Rely on definer rights to access centralized data from any schema.page 210 . HQ Chicago Check City Statistics  New York stolenlives Analyze Pattern stolenlives perpetrators perp.

page 211 .Row Level Security DBMS_RLS Row-Level Security 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

DBMS_RLS. you could achieve this only partially through the use of views. with which to implement automated row-level security (also referred to as "fine grained access control"). Row Level Security  The establishment of security policies on (restricted access to) individual rows of a table. The DBMS_RLS package (along with "system contexts") now allow you to do so in a foolproof manner. PL/SQL Advanced Techniques .page 212   1/21/2011 Copyright 2001 Steven Feuerstein .Row-Level Security with DBMS_RLS  Oracle8i offers a new package. Prior to Oracle8i.

 Security Policy Packages ± You will need to write a package containing functions that establish the security policies to be applied to a particular table.  Database Logon Triggers ± I want to make sure that when a person logs in.  DBMS_RLS ± Use programs in DBMS_RLS to associate your security policies with tables. the system context is a named set of attributevalue pairs global to your session. their context information is set properly.  Let's step through a simple example to see how all these pieces tie together.page 213 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Components Needed for RLS  System Contexts ± A new feature in Oracle8i.

± Regulators can only see patients who reside in the same state.sql  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Here are some rules: ± Doctors can only see patients who are assigned to their clinic. all pregnant women receive excellent prenatal care. The main tables are patient. clinic and regulator. popular uprising in the United States has forced the establishment of a national healthcare system. ± Patients can only see information about themselves. all children are vaccinated.page 214 . No more for-profit hospitals pulling billions of dollars out of the system. no more private insurance companies soaking up 30 cents on the dollar.  We need a top-notch. highly secure database for NHCS. fgac. ± A massive.A National Health Care System  The year is 2010. doctor.

doctor_id). FETCH doc_cur INTO doc_rec. DBMS_SESSION. BEGIN OPEN doc_cur. DBMS_SESSION. PROCEDURE set_context IS This is a simplification.SET_CONTEXT ( 'patient_restriction'. and create a procedure that will set the context attributes (type and ID) upon login. c_person_type_attr.page 215 . END. c_person_id_attr. See CURSOR doc_cur IS fgac. sets the context accordingly. CREATE CONTEXT patient_restriction USING nhc_pkg.Set the Context  Define a context in the database. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sql for logic that identifies SELECT doctor_id FROM doctor different types of people and WHERE schema_name = USER. doc_rec doc_cur%ROWTYPE.SET_CONTEXT ( 'patient_restriction'. 'DOCTOR'). doc_rec.

person. name_in VARCHAR2) RETURN VARCHAR2 IS l_context VARCHAR2(100) := Extract the context SYS_CONTEXT (c_context. FUNCTION person_predicate ( schema_in VARCHAR2. c_person_type_attr). BEGIN IF l_context = 'DOCTOR' THEN retval := 'home_clinic_id IN (SELECT home_clinic_id FROM doctor We need a different string WHERE doctor_id = SYS_CONTEXT (''' || to modify the WHERE c_context || '''. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Define the Predicate  A predicate is a string that will be appended to the WHERE clause of the table to which this security policy is associated (see next page).page 216 . connection. information for this retval VARCHAR2(2000). ''' || clause for each type of c_person_id_attr || '''))'.

DELETE'). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .PATIENT table will be modified by the string returned by the person_predicate function of the SCOTT. ( => => => => => => 'SCOTT'.nhc_pkg package. 'patient_privacy'. ± The following procedure call specifies that the WHERE clause of any query.person_predicate'.ADD_POLICY procedure. 'SCOTT'.page 217 .UPDATE. update or delete against the SCOTT.ADD_POLICY OBJECT_SCHEMA OBJECT_NAME POLICY_NAME FUNCTION_SCHEMA POLICY_FUNCTION STATEMENT_TYPES END.Create the Security Policy  Use the DBMS_RLS. BEGIN DBMS_RLS. 'nhc_pkg. 'patient'. 'SELECT.

sql Exception handling in trigger is critical! If you allow an exception to go unhandled.Create Logon Trigger. we guarantee that the context is set (and the predicate applied) no matter which product is the entry point to Oracle. logon is disabled. END. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 218 . fgac. CREATE OR REPLACE TRIGGER set_id_on_logon AFTER LOGON ON DATABASE BEGIN nhc_pkg.set_context.PUT_LINE ( 'Error ' || SQLCODE || ' setting context for ' || USER'). EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT. Setting Context  By setting the context in the logon trigger.

page 219 . Context Information for "SWALLACE": Type: DOCTOR Doctor sees only her ID: 1060 patients. 'person_id')) Patients Visible to "SWALLACE": CSILVA .IL 1/21/2011 Copyright 2001 Steven Feuerstein Patient sees only himself.Veva Silva .Chris Silva .Chris Silva . Predicate: home_clinic_id IN (SELECT home_clinic_id FROM doctor WHERE doctor_id = SYS_CONTEXT ('patient_restriction'.IL VSILVA . PL/SQL Advanced Techniques .Queries Transparently Filtered  What you see is determined automatically by who you are.IL Context Information for "CSILVA": Type: PATIENT ID: Predicate: schema_name = 'CSILVA' Patients Visible to "CSILVA": CSILVA .

..and play a new tune with PL/SQL! 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . It's so easy to fall into a rut with a programming language.. February... March.Take Full Advantage of PL/SQL! January...  ± You learn what you need to get the job done. Jump out of your rut ...page 220 . April. May. and you use only what you know..

k.Achieving PL/SQL Excellence Appendices (a.page 221 . If time permits«)     UTL_FILE ± file IO DBMS_JOB ± Job scheduling DBMS_PIPE ± Pipe-based communication DBMS_UTILITY ± the kitchen sink package 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques ..a.

.Built-in Packages: UTL_FILE UTL_FILE Server-side File I/O Application FOPEN GET_LINE PUT_LINE . Physical Files 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 222 ..

± Maximum of 1023 bytes per line (read or write) until Oracle 8. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .5.UTL_FILE: Server-side I/O  Allows you to read from and write to operating system files on the database server. delete. copy. ± Limitations on files you can access (no mapped files.   But you can read lines from a file and write lines to a file.0. A "version 1" (fairly primitive) utility. random access to contents). no use of environmental variables)..page 223 . ± No higher-level file operations supported (change privileges.. when it jumps to 32K.

Puts formatted text into the buffer PL/SQL Advanced Techniques .UTL_FILE Module Outline FCLOSE FCLOSE_ALL FFLUSH FOPEN GET_LINE IS_OPEN NEW_LINE PUT PUT_LINE PUTF Close the specified file Close all open files in your session Flush all data from the UTL_FILE buffer to your file Open a file Get the next line from a file Returns TRUE if the file is open (sort of) Insert a new line character in file at the end of current line Puts text into the UTL_FILE buffer Puts text and new line character into UTL_FILE buffer.page 224 1/21/2011 Copyright 2001 Steven Feuerstein .

± You do this by adding lines to the instance parameter file. no trailing delimiter. PL/SQL Advanced Techniques . utl_file_dir = * Allows read & write for any directory. ± No single or double quotes around directory.  Follow these rules to avoid many headaches. there is no subdirectory recursion). utl_file_dir = /tmp utl_file_dir = /accounts/newdev  And don't do either of the following: utl_file_dir = .page 225 Allows read & write for current directory.Authorizing Directory Access  Oracle requires you to list explicitly those directories you wish to be able to read/write with UTL_FILE. ± Use a separate entry for each directory (and subdirectory. 1/21/2011 Copyright 2001 Steven Feuerstein .

/ utlfile.tst  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . UTL_FILE.Test UTL_FILE Access  About the hardest part to working with UTL_FILE is simply getting started. */ fid := UTL_FILE.FOPEN ('c:\temp'. So before you write anything fancy. END.PUT_LINE (fid. UTL_FILE.FCLOSE (fid). 'test. and then run the following test script (it can't get much simpler than this): DECLARE fid UTL_FILE. restart your database. 'W').txt'.page 226 . BEGIN /* Change the directory name to one to which you at least || THINK you have read/write access. modify your initialization file.FILE_TYPE. 'hello').

END. 'W' for Write and 'A' for Append.FILE_TYPE.  Specify file location.Opening a File DECLARE fid UTL_FILE. 'test. Test to see if file is open with the IS_OPEN function.. name and operation type. ± Types are 'R' for Read.page 227 . ± In actuality.txt'.  The FOPEN function returns a record ("file handle") based on the UTL_FILE. 'W'). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .FOPEN ('c:\temp'. Not much of a test.   Maximum of 10 files may be opened in each user session. BEGIN fid := UTL_FILE.FILE_TYPE.. ± Currently contains a single ID field. this function simply returns TRUE if the file handle's id field is NOT NULL.

getnext.  The NO_DATA_FOUND exception is raised if you read past the end of the file. UTL_FILE.FILE_TYPE.GET_LINE (fid. myline). BEGIN fid := UTL_FILE. the ceiling is raised to 32K. Lines in the file cannot be longer than 1023 bytes in length.Reading from a File DECLARE fid UTL_FILE. END.txt'.page 228 .5 and above.0.   Can only read from a file opened with the "R" mode. 'test. UTL_FILE.sp 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .FOPEN ('c:\temp'. 'R').FCLOSE (fid). ± In Oracle8 Release 8. ± You might want to build your own GET_LINE which handles the exception and returns an EOF Boolean status flag.

PUT_LINE (fid. 'test. ' that I never\nwant to %s'. allowing for some formatting. ± The file buffers are automatically flushed when you close a file or exit your session. 'W').page 229 1/21/2011 Copyright 2001 Steven Feuerstein . PUT_LINE or PUTF. END. 'is so much fun').Writing to a File DECLARE fid UTL_FILE.PUTF (fid. 'UTL_FILE'). '&1'). ± PUTF is like the C printf program.PUT (fid. UTL_FILE.  Call FFLUSH to make sure that everything you have written to the buffer is flushed out to the file. UTL_FILE is so much fun that I never want to stop Resulting Text  You can use PUT.FILE_TYPE.FOPEN ('c:\temp'. UTL_FILE.FCLOSE (fid). BEGIN fid := UTL_FILE. PL/SQL Advanced Techniques . UTL_FILE. UTL_FILE.txt'.

FOPEN ('c:\temp'. 'R').FCLOSE (fid). END. PL/SQL Advanced Techniques . BEGIN fid := UTL_FILE. you will not see the data you have (supposedly) written to that file.txt'. myline).READ_ERROR THEN UTL_FILE. UTL_FILE. EXCEPTION WHEN UTL_FILE.GET_LINE (fid. UTL_FILE.  If you do not close the file.FCLOSE (fid). You should close files in exception handlers to make sure that files are not left "hanging" open.Closing a File DECLARE fid UTL_FILE.page 230   1/21/2011 Copyright 2001 Steven Feuerstein . You can close a single file with FCLOSE or all open files with FCLOSE_ALL.FILE_TYPE. 'test.

EXCEPTION.  UTL_FILE relies on a combination of user-defined exceptions and STANDARD exceptions to communicate errors.Error Handling in UTL_FILE PACKAGE UTL_FILE IS invalid_path invalid_mode invalid_filehandle invalid_operation read_error write_error internal_error END. EXCEPTION.page 231 . ± They all share a common SQLCODE of 1. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . EXCEPTION. EXCEPTION. EXCEPTION. EXCEPTION. ± UTL_FILE-named exceptions in other cases.  You have to take special care to trap and handle the named exceptions. EXCEPTION. ± NO_DATA_FOUND when you try to read past the end of the file.

WHEN UTL_FILE. RAISE.c_read_error).c_internal_error).sql  Trap locally by name. PL/SQL Advanced Techniques .INVALID_FILEHANDLE THEN recNgo (PLVfile. WHEN UTL_FILE. WHEN UTL_FILE.INVALID_OPERATION THEN recNgo (PLVfile. RAISE. RAISE. WHEN UTL_FILE. utlflexc.Recommended Exception Section EXCEPTION WHEN UTL_FILE. RAISE. RAISE. END.c_invalid_operation).c_invalid_mode). Re-raise exception if you want it to propagate from that block. translating the generic user-defined exception into an understandable message. RAISE. record the error.INTERNAL_ERROR THEN recNgo (PLVfile.WRITE_ERROR THEN recNgo (PLVfile. WHEN UTL_FILE. WHEN UTL_FILE.c_invalid_filehandle).READ_ERROR THEN recNgo (PLVfile.c_write_error).c_invalid_path).INVALID_PATH THEN recNgo (PLVfile.INVALID_MODE THEN recNgo (PLVfile. RAISE.page 232  1/21/2011 Copyright 2001 Steven Feuerstein .

.page 233 .. Background Process DBA_JOBS Oracle Job Queue Subsystem 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Built-in Packages: DBMS_JOB DBMS_JOB Scheduled Execution of Stored Procedures Application SUBMIT RUN REMOVE .

Schedule large batch jobs to run on "off hours".Overview of DBMS_JOB  DBMS_JOB provides an API to the Oracle job queues. You can use DBMS_JOB to: Replicate data between different database instances.2. Made its debut in PL/SQL Release 2. Built by Oracle to support snapshots and replication.page 234 . but only ³publicly available´ and supported in PL/SQL Release 2. which in turn offers job scheduling capabilities within the Oracle Server. Schedule regular maintenance on instances. ± Spawn background processes to avoid blocking client process. Create a listener program to poll the contents of a pipe and take action. ± ± ± ±    1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .1.

PL/SQL Advanced Techniques . Submits a job to the queue returning a unique job number.page 235 CHANGE INTERVAL ISUBMIT NEXT_DATE REMOVE RUN SUBMIT USER_EXPORT WHAT 1/21/2011 Copyright 2001 Steven Feuerstein . Changes the job string of a job.DBMS_JOB Module Outline BROKEN Marks the job as either FIXED or BROKEN. Changes one or all attributes of a job. Broken jobs will not run as scheduled. Removes the job from the queue. Changes the interval between executions of a job. Forces immediate execution of the specified job number. Submits a job to the queue using a predefined job number. Returns the job string for a job number. Changes when a queued job will run.

± In the above example. 'calculate_totals.'. BEGIN DBMS_JOB. 'SYSDATE + 1'). PL/SQL Advanced Techniques . END.SUBMIT (job#.  When you submit a job.  A job is a call to a stored procedure or an anonymous block ± It must end with a semi-colon and can contain ³hard-coded´ arguments. while the interval is a string (this is dynamic PL/SQL!)  You can also call DBMS_JOB.ISUBMIT and supply the job number. you specify the date on which it should next execute.Submitting a Job DECLARE job# BINARY_INTEGER. Notice that the start time is a DATE expression.page 236 1/21/2011 Copyright 2001 Steven Feuerstein . I run calculate_totals immediately and then on a daily basis thereafter. SYSDATE. instead of having DBMS_JOB generate one for you. and then the job¶s execution interval (frequency of execution).

next_date => TRUNC (SYSDATE + 1).estimate_percent=>50). interval => 'TRUNC(SYSDATE+1)' ).''LOAD1''.'. /  This block submits a job that uses a built-in procedure.''TENK''' || '.l (v_jobno).Submit Job Example DECLARE v_jobno INTEGER. PL/SQL Advanced Techniques . to analyze a specific table every evening at midnight.null. END. BEGIN DBMS_JOB.page 237 1/21/2011 Copyright 2001 Steven Feuerstein .''ESTIMATE''. what => 'DBMS_DDL.ANALYZE_OBJECT.submit ( job => v_jobno. DBMS_DDL. p.ANALYZE_OBJECT ' || '(''TABLE''.

DBMS_JOB. numbered 1. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .' .SYSDATE+1.what => 'my_job1(''string_parm_value''. executes immediately. 'my_job2(date_IN=>SYSDATE).'. runs it in one hour and executes every day thereafter. END. ± Job 2 passes a date into procedure MY_JOB2.ISUBMIT(3.'SYSDATE+10/1440'). and will be removed from the queue automatically. END.interval => 'SYSDATE +1').next_date => SYSDATE + 1/24 . /  This block submits three jobs to the job queue. and 3.ISUBMIT (job => 1 .SYSDATE.page 238 .ISUBMIT (2.' .2. executes for the first time tomorrow and every 10 minutes thereafter. ± Job 3 is a PL/SQL block which does nothing.'BEGIN null.DBMS_JOB. ± Job 1 passes a string and number into procedure MY_JOB1.120).ISubmit Job Example BEGIN DBMS_JOB. DBMS_JOB.null).

Wednesday and Friday at 6 PM 'SYSDATE + 1/24' 'NEXT_DAY (TRUNC (SYSDATE).page 239 + 1/21/2011 Copyright 2001 Steven Feuerstein . NEXT_DAY (SYSDATE. ± Use date arithmetic to request intervals smaller than a day. ''FRIDAY''))) + 18/24' PL/SQL Advanced Techniques . ''MONDAY''). 3). ''WEDNESDAY''). you must use 2 single quotes to embed strings.Specifying Job Times & Frequencies  Probably the most complicated part of using DBMS_JOB is to get the string expression of the job interval right. Every hour Every Sunday at 2 AM First Monday of each quarter. ''MONDAY'') + 9/24' 'TRUNC (LEAST ( NEXT_DAY (SYSDATE. ''Q''). ''SATURDAY'') 2/24' 'NEXT_DAY ( ADD_MONTHS (TRUNC (SYSDATE. ± Since it's a string. NEXT_DAY (SYSDATE. at 9 AM Every Monday.

RUN (my_job#).job).  Run a job immediately. ± Produces a string that can be used to recreate an existing job in the job queue. DBMS_JOB. expjob. ± Uses DBMS_JOB.Other Job Queue Operations  Remove a job from the queue. ± Only if the job was submitted from same schema BEGIN FOR rec IN (SELECT * FROM USER_JOBS) LOOP DBMS_JOB. ± Performs an implicit COMMIT in current session. Remove all jobs for current schema.page 240 .sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .ISUBMIT. END LOOP.  Export jobs from the queue. retaining current job number.REMOVE (rec.

jr.sid = jr. who owns them and when they began.Job Queue Views  You can also view the job queue by looking at the DBA_JOBS_RUNNING.sid AND jr.this_date .V$SESSION WHERE s.page 241 .job .what job_id username start_date job_definition jr j s showjobs.job = j.job ORDER BY jr.DBA_JOBS .username . ± The following query blends job information with session information to display currently-executing jobs. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sql FROM DBA_JOBS_RUNNING . SELECT jr. DBA_JOBS and USER_JOBS views.this_date.

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . You will have to take special DBA action if you want to restrict who can run jobs. ± The default is PUBLIC access.  You will need to set three parameters in the init. The valid range is 0 through 36. The valid range is 1 to 3600 (a maximum. therefore. of one hour).page 242 .ora (initialization) file for your database instance: ± job_queue_processes=N where n is the number of concurrent background processes permitted. ± job_queue_interval=N where N is the interval in seconds to check the job queue.Setting up the Job Facility  Make sure that the correct access is set up for the DBMS_JOB package.

± Do you want it to try 16 times? ± In addition.  To avoid unexpected and unhandled failures of scheduled jobs: ± Always use the RUN built-in to execute your job in a ³test´ mode.page 243 .Error Handling with DBMS_JOB  What if your stored procedure fails? ± After 16 attempts. Then you can go ahead and submit it. it may cause the background processes to fail and no longer run any jobs at all. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . if your failure raises an unhandled exception. ± Always include a WHEN OTHERS exception handler in your job program which traps any and all problems and automatically sets the job status to broken. the job facility will mark your job as broken.

BROKEN (job#.. spacelog. ± Uses a call to BROKEN to set the status of the job to ³broken´. ± Now the job facility will not try to run this program again. µFAIL¶).log (µcalc_totals¶.job (µcalc_totals¶) DBMS_JOB. ± Obtains the job number from a packaged function by passing the name of the procedure. TRUE). ± Calls log program of package to record that failure took place. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . job_pkg.page 244 . You can go in and fix the problem.. END.sql showspc.sql  The WHEN OTHERS exception handler of the calc_totals procedure traps any kind of failure. EXCEPTION WHEN OTHERS THEN job# := job_pkg.Stopping the Job When It Fails PROCEDURE calc_totals IS BEGIN .

"Good to Knows" for DBMS_JOB  You may find it useful to always wrap your stored procedure call (the what) inside a BEGIN-END block. ± We've noticed some aberrant. When a job runs.page 245 . difficult to reproduce behavior at times with "straight" procedure calls. If you find that you submit a job to run immediately and it does not start. perform a COMMIT after your submit. ± DBMS_JOB only allows you to modify characteristics and behavior of jobs submitted by the current schema. it picks up the current execution environment for the user.  You will need to fully-qualify all database links (with user name and password) to get them to work properly.    1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . You can use the DBMS_IJOB to manage the jobs of other users.

page 246 .Built-in Packages: DBMS_PIPE DBMS_PIPE Inter-session Communication 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

± Operates outside of database transaction limitations. Oracle uses database pipes to parallelize database operations.page 247 . You can parallelize your own code. ± Interface PL/SQL-database activities with operating system functions and programs written in other languages.  Uses for DBMS_PIPE include: ± Parallelization of program execution. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± More sophisticated debugging inside PL/SQL programs (work around fundamental limitations of DBMS_OUTPUT).DBMS_PIPE Overview  Allows communication between different Oracle sessions through a pipe in the RDBMS Shared Global Area. ± Perform and commit DML in a separate transaction space from your main transaction.

± Names can be up to 128 chars long (do not use names beginning with ³ORA$´. They are reserved for Oracle use). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Architecture of DBMS_PIPE Shared Global Area ³Sue´ ³Bob´ Message Buffer Message Buffer Session A  Session B A pipe is a named object that uses the System Global Area to provide a non-transaction based conduit of information. using a maximum of 4096 bytes. ± The pipe sends/receives a message.page 248 . which can be composed of one or more separate packets.

Processing Flow of DBMS_PIPE  Construct a message from packets of information.sql PL/SQL Advanced Techniques .page 249 .  Send the message to a named pipe. so you should always specify a timeout period.  Receive a message from that pipe. you can wait for up to 1000 days (or 86400000 seconds) for the pipe to be cleared. ± There is just one message buffer per session. ROWID or RAW. date or number).  Unpack the message packets and take action. ± You can wait for up to 1000 days for a message. 1/21/2011 Copyright 2001 Steven Feuerstein pipex1. ± If there isn¶t currently room in the pipe. ± Each packet can be a string. ± Separate out the individual packets in the message (again: string. ± This is the default. date. number.sql pipex2.

NEXT_ITEM_TYPE Returns the datatype of the next item in the piped message. UNIQUE_SESSION_NAME Returns name that is unique among all sessions in the database. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Clears your buffer so that PACK_MESSAGE and UNPACK_MESSAGE can work from the first item. making it a candidate for removal with a LRU algorithm. PURGE Empties the contents of a pipe into your local buffer freeing it for removal. PACK_MESSAGE Packs an item into the message buffer for your session. REMOVE_PIPE RESET_BUFFER Removes a pipe explicitly created via CREATE_PIPE. UNPACK_MESSAGE Unpacks the next item from the local message buffer and deposits it into the specified local variable.DBMS_PIPE Module Outline Module Name CREATE_PIPE Description Creates a PUBLIC or PRIVATE pipe. SEND_MESSAGE Sends contents of message buffer to the specified pipe.page 250 . RECEIVE_MESSAGE Receives a message from pipe and copies to local buffer.

± Send messages to non-existent pipe implicitly create it.Creating Public and Private Pipes  There are two ways to create pipes: implicitly and explicitly.  An explicit pipe can be private (accessible only to sessions with matching userID or SYSDBA privileges). private => TRUE). ± Specify TRUE for private argument of CREATE_PIPE.  A public pipe is accessible as long as you know its name.page 251 . PROCEDURE newpipe IS stat INTEGER. BEGIN stat := DBMS_PIPE.CREATE_PIPE ( pipename => 'bbs'. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . maxpipesize => 20000. ± Implicitly-created pipes are always public. ± Use CREATE_PIPE to create a pipe explicitly.

FOR month_num IN 1 . 1/21/2011 Copyright 2001 Steven Feuerstein Fill your message buffer with packets of data. Status of 0 means message was sent. maxpipesize IN INTEGER DEFAULT 8192) RETURN INTEGER.PACK_MESSAGE ( total_sales (month_num)). expanding pipe size to 40 Kbytes. 60. 10 * 4096). pipe_stat := DBMS_PIPE. Send to "monthly" pipe.Sending a Message Provide pipe name. timeout IN INTEGER DEFAULT maxwait. IF pipe_stat != 0 THEN RAISE could_not_send. waiting up to 1 minute. PL/SQL Advanced Techniques .page 252 . seconds you will wait. 12 LOOP DBMS_PIPE.SEND_MESSAGE ( µmonthly¶. and new max pipe size (you can make it bigger. FUNCTION send_message (pipename IN VARCHAR2. but not smaller).. END LOOP.

± You need to know the datatype of packet or check it using NEXT_ITEM_TYPE. PROCEDURE unpack_message (item OUT VARCHAR2).  Then you call UNPACK_MESSAGE to extract individual packets from the message. ± Pipe status of 0 means the message was read successfully. PROCEDURE unpack_message (item OUT DATE). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . timeout IN INTEGER DEFAULT maxwait) RETURN INTEGER.  First you pull the message from the pipe and place it in buffer with RECEIVE_MESSAGE.Receiving and Unpack a Message FUNCTION receive_message (pipename IN VARCHAR2. ± Specify pipe and number of seconds you will wait before you time out.page 253 . PROCEDURE unpack_message (item OUT NUMBER).

every_n_secs).A Pipe-based Listener Program  Program wakes up every N seconds to read the data from the pipe and analyze results from assembly line (an intentional "infinite loop"!). Wait up to N prod_total NUMBER. prod_total). END IF. PL/SQL Advanced Techniques .RECEIVE_MESSAGE ( 'production'. analyze_production (SYSDATE. END LOOP. PROCEDURE analyze_assembly_data (every_n_secs IN INTEGER) IS pipe_status INTEGER. DBMS_PIPE.UNPACK_MESSAGE (prod_total). ELSE RAISE_APPLICATION_ERROR ( Stop process if -20000. 'Production data unavailable. pass it on to the IF pipe_status = 0 computation THEN program.page 254 1/21/2011 Copyright 2001 Steven Feuerstein . LOOP pipe_status := DBMS_PIPE.'). data not received. END. If I got something. seconds for the BEGIN next report.

Unpacking the Message FUNCTION next_item_type RETURN INTEGER.page 255 .tst  Since a message can be composed of packets of different datatypes. Either: ± You know the datatype and therefore can ³hard-code´ the correct variable into the call to UNPACK_MESSAGE. you have to make sure that you unpack a packet into the right kind of variable.sql dbpipe. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Or you use the built-in NEXT_ITEM_TYPE to tell you in advance the datatype of the next packet in the message and take appropriate action. Returns one of the following values: Value 0 6 9 11 12 23 Description or Data type No more items in buffer NUMBER VARCHAR2 ROWID DATE RAW dbpipe.

Parallelizing Your Code with Pipes  Oracle uses DBMS_PIPE to improve RDBMS performance. total office expenses and total compensation.  Suppose I want to calculate my net profit.  Without pipes. you can do the same for your application if: ± You have multiple CPUs available. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . I must execute them sequentially and incur an elapsed time of 45 minutes before I calculate the profits. ± You have processes which can run in parallel. ± These programs each take 15 minutes. but are not dependent on each other. In order to do so I must first compute total sales. ± The CEO is decidedly unhappy about the delay.page 256 .

page 257 . Parallel Execution Sequential Execution: Maximum Elapsed Time S t a r t E n d Process A Process B Process C Parallel Execution: Minimum Elapsed Time Start Process A Process B Process C End 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Sequential vs.

 The ³wait´ program waits till it receives a message from each program. ± When each program is complete.Parallelizing PL/SQL Execution BEGIN kick_off_sales_calc. calculate_net_profits. it puts a message (perhaps even a value) into the pipe.page 258 1/21/2011 Copyright 2001 Steven Feuerstein .in a muchdecreased elapsed time. kick_off_totcomp_calc. kick_off_exp_calc.  The ³kick off´ programs pass their messages to separate pipes. wait_for_confirmation. ± Other programs running in the background grab the messages and start their corresponding calculation program. Then net profits can be computed -. END. PL/SQL Advanced Techniques .

calculate sales. and send back the results. PL/SQL Advanced Techniques . PROCEDURE calculate_sales IS stat INTEGER.PACK_MESSAGE (1995). END. END IF. stat := DBMS_PIPE.RECEIVE_MESSAGE (µsales¶). IF stat = 0 THEN lots_of_number_crunching.page 259 . stat := DBMS_PIPE. stat := DBMS_PIPE.SEND_MESSAGE (µsales¶). BEGIN stat := DBMS_PIPE.PACK_MESSAGE (sales$).PACK_MESSAGE (NULL). END.SEND_MESSAGE (µsales¶).SEND_MESSAGE (µsales¶). DBMS_PIPE. Receive the year. BEGIN DBMS_PIPE. ELSE DBMS_PIPE. 1/21/2011 Copyright 2001 Steven Feuerstein Send message to start calculations.Code to Kick Off and Calculate PROCEDURE kick_off_sales_calc IS stat INTEGER.

Waiting for Confirmation PROCEDURE wait_for_confirmation IS stat INTEGER. PROCEDURE calculate_net_profits IS BEGIN net_profits := sales$ . Wait for all calculations to finish.comp$. DBMS_PIPE.UNPACK_MESSAGE (sales$). DBMS_PIPE. DBMS_PIPE.offexp$ .sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . stat := DBMS_PIPE. The order in which you wait is insignificant. stat := DBMS_PIPE. BEGIN stat := DBMS_PIPE.RECEIVE_MESSAGE (µcomp¶).page 260 . END. END.RECEIVE_MESSAGE (µoffexp¶).UNPACK_MESSAGE (comp$).RECEIVE_MESSAGE (µsales¶). parallel.UNPACK_MESSAGE (offexp$). Perform final calculation.

page 261 . syscache.tst 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . watch. and sends it to the pipe.pkg syscache.pkg  Implementation of a system-wide.Other DBMS_PIPE Examples  Simple trace package that sends it output either to screen or to pipe. ± A listener program grabs the request (including the return pipe name). ± Demonstrates the use of toggles and switches in packages. ± The requester reads the information from the pipe.pkg p_and_l. obtains the data. in-memory cache. ± A request for data is passed to a "central" pipe.

A µgrab-bag¶ of miscellaneous operations SCHEMA 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Built-in Packages: DBMS_UTILITY DBMS_UTILITY Application GET_TIME GET_HASH_VALUE FORMAT_CALL_STACK ...page 262 .

Returns error stack. Returns hash value for string. Returns database version (Oracle8) Executes DDL statement (Oracle8).pkg dbparm. Gets block number part of data block address.page 263 dbver.DBMS_UTILITY Module Outline ANALYZE_DATABASE ANALYZE_PART_OBJECT Analyze objects in database Runs ANALYZE TABLE or ANALYZE INDEX for each partition of the object (Oracle8). Returns execution call stack. Gets file number part of data block address. Recompile INVALID objects in specified schema. PL/SQL Advanced Techniques . Parses comma-delimited list to index-by table.pkg COMMA_TO_TABLE COMPILE_SCHEMA DATA_BLOCK_ADDRESS_BLOCK DATA_BLOCK_ADDRESS_FILE DB_VERSION EXEC_DDL_STATEMENT FORMAT_CALL_STACK FORMAT_ERROR_STACK GET_HASH_VALUE 1/21/2011 Copyright 2001 Steven Feuerstein .

Creates data block address from block & file numbers. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Resolves name of object into component parts.page 264 . GET_PARAMETER_VALUE GET_TIME IS_PARALLEL_SERVER MAKE_DATA_BLOCK_ADDRESS NAME_RESOLVE NAME_TOKENIZE PORT_STRING TABLE_TO_COMMA Retrieves value of database parameter (Oracle8).DBMS_UTILITY Module Outline. Parses string object designator into components. Returns platform and version of database. Returns "current time" down to hundredth of second. Converts list (in index-by-table) of elements into a comma-delimited list (string). cont. Returns TRUE if in parallel server mode.

PL/SQL Advanced Techniques . DECLARE v_start BINARY_INTEGER.v_start). ± SYSDATE only reflects times down to the nearest second. ± Useful when analyzing individual PL/SQL programs.GET_TIME. DBMS_OUTPUT.Sub-Second Timings with GET_TIME  GET_TIME returns the number of 100ths of seconds that have elapsed since an arbitrary point in time. END. especially those that run in sub-second time. calc_totals.page 265 1/21/2011 Copyright 2001 Steven Feuerstein .GET_TIME .PUT_LINE (DBMS_UTILITY.  Compare results from consecutive calls to GET_TIME to determine the elapsed time of PL/SQL code execution. so GET_TIME offers significant additional granularity. Basic steps necessary to convert GET_TIME into a performance analysis tool. BEGIN v_start := DBMS_UTILITY.

END.sps plvtmr. PLVtmr. PROCEDURE capture ( context_in IN VARCHAR2 := NULL) PROCEDURE show_elapsed (prefix_in IN VARCHAR2 := NULL.spb 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . BEGIN PLVtmr.sql plvtmr. END PLVtmr. calc_totals.show_elapsed. reset_in IN BOOLEAN := TRUE). PROCEDURE set_factor (factor_in IN NUMBER).Building a Layer Over GET_TIME Partial package specification PACKAGE PLVtmr IS PROCEDURE turn_on.page 266 . adjust_in IN NUMBER := 0.capture. Clean and lean timing code ovrhead. PROCEDURE turn_off.

Accessing the Execution Call Stack Use in the exception section to show context of error. EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.CALC_NET_WORTH anonymous block  "Little known facts" about FORMAT_CALL_STACK: ± Contains embedded new-line characters.page 267 .COMPANY_TYPE procedure STEVEN.VALIDATE_REQUEST function STEVEN. equivalent to CHR(10). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . only the package name. END.PUT_LINE ( DBMS_UTILITY. ----. ± Most recent program at beginning of "report". ± Does not show package elements.FORMAT_CALL_STACK).PL/SQL Call Stack ----object line object handle number name 88ce3f74 88e49fc4 88e49390 88e2bd20 8 2 1 1 package STEVEN.

page 268 1/21/2011 Copyright 2001 Steven Feuerstein . PL/SQL Advanced Techniques . EXIT WHEN next_newline = 0. END.sp dispcs.startpos + 1). startpos.sps DBMS_OUTPUT. CHR(10). CREATE OR REPLACE PROCEDURE dispcs IS stk VARCHAR2(10000).pkg plvcs. Instead. BEGIN stk := DBMS_UTILITY. END LOOP. startpos := next_newline + 1. startpos INTEGER := 1. next_newline . next_newline INTEGER.FORMAT_CALL_STACK || CHR(10). dispcs. LOOP next_newline := INSTR (stk. next_line := SUBSTR ( stk.Accessing Call Stack Contents  The call stack length can easily exceed 255 bytes. which means you cannot pass it to DBMS_OUTPUT directly. startpos. use a loop to read through the stack. next_line VARCHAR2(255). 1).tst callstack.PUT_LINE (next_line).

..but don't see it as a problem.sp snc. ± Use NAME_RESOLVE to break down an identifier string into its components easily.  Possible "Part 1" Types 5 7 8 9 Synonym Procedure Function Package What a chore! All those arguments. object_number OUT NUMBER). dblink OUT VARCHAR2.pkg 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques ... see it as an opportunity.NAME_RESOLVE (name IN VARCHAR2. context IN NUMBER.Resolving Names of Stored Code  Code names have many components. PROCEDURE DBMS_UTILITY. part2 OUT VARCHAR2. part1 OUT VARCHAR2. schema OUT VARCHAR2.page 269 .for encapsulation! showcomp. the way they are attached also follows a complicated syntax. part1_type OUT NUMBER.

Sign up to vote on this title
UsefulNot useful