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

custrules. ± There's a big difference between a bunch of separate programs and a coherent. ± Can lead to performance improvements.pkb  Construct very flexible and usable utilities for developers.page 6 . you call the packaged procedures and functions instead. te_employee.pkg insga. ± Instead of writing SQL directly in your programs.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.pkg 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . package-based "component". ± Puts more structure and organization in your body of code. watch.

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

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

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

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

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

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

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

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

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

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

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

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

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

ini'.  Overloading of FCreate PACKAGE PLVfile IS /* Procedure */ PROCEDURE fcreate (file_in IN VARCHAR2. line_in IN VARCHAR2 := NULL). BEGIN fid := PLVfile.pkg PL/SQL Advanced Techniques .FILE_TYPE.page 20 . custrules.flg').FILE_TYPE. END 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. TO_CHAR (SYSDATE)). 1/21/2011 Copyright 2001 Steven Feuerstein Use as Function DECLARE fid UTL_FILE. END. /* Function */ FUNCTION fcreate (file_in IN VARCHAR2. PLVfile.put_line (fid. v_user).fcreate ('temp. line_in IN VARCHAR2 := NULL) RETURN UTL_FILE. Use as Procedure BEGIN PLVfile.fcreate ('exists.

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

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

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

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

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

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

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

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.

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

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

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

page 32 . birthdays when_t.  Nested table characteristics ± Homogeneous » Each row contains the same structure of data. DECLARE TYPE when_t IS TABLE OF DATE.147.647 ± Initially dense. Valid row numbers range: 1 to 2. ± Unbounded. but only with explicit EXTEND requests » Practically speaking. 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 .483.Nested Tables [CREATE OR REPLACE] TYPE <table_type> IS TABLE OF <datatype> [NOT NULL].

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.Nested Tables CREATE OR REPLACE TYPE child_table_type IS TABLE OF VARCHAR2 (30). CREATE TABLE db_family (surname VARCHAR2 (30).page 33 .sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

483. Maximum value: 2.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. can be EXTENDed or TRIMmed. ± Bounded » Upper limit established when the TYPE is defined.Variable Arrays [CREATE OR REPLACE] TYPE <table_type> IS VARRAY (N) OF <datatype> [NOT NULL]. salaries numbers_t.  Characteristics of variable arrays: ± Homogeneous » Each row contains the same structure of data. DECLARE TYPE numbers_t IS VARRAY (10) OF NUMBER.647 ± Dense » Never any gaps between defined rows.147. ± Variable arrays are actually stored in the DB table 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

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

type_name IN ('NAMES_VT'.owner T.Obtaining Collection Information SELECT FROM WHERE AND AND AND A.page 37 . 'TMRS_VT') T.owner = USER T.type_name.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .attr_type_name Attributes all_coll_types T.elem_type_name = A. ± The code used to define the collection TYPE  There is no information in the data dictionary available for index-by tables. colldd.owner = A.  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.attr_name || ' .' || A. all_type_attrs A T.

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

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

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

pkg psemp. 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. END LOOP. CREATE OR REPLACE PACKAGE BODY psemp IS BEGIN FOR rec IN (SELECT * FROM emp) LOOP emp_tab (rec.Transferring DB Table to Collection CREATE OR REPLACE PACKAGE psemp IS TYPE emp_tabtype IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER. 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. END.empno) := rec. emp_tab emp_tabtype.tst  PL/SQL Advanced Techniques .page 41 .

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

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

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

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

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

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

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

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

tst 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . deposit your data in a collection and then provide programs to access that data in the necessary fashion. PROCEDURE prevRow. didn't make it!  Instead. Notice that the collection itself is hidden. CREATE OR REPLACE PACKAGE bidir IS /* Iterate through rows in the result set */ PROCEDURE setRow (nth IN PLS_INTEGER).  bidir. FUNCTION getRow RETURN employee_plus%ROWTYPE. ± A talked-about feature for Oracle9i -. PROCEDURE nextRow.page 54 .nope.pkg bidir. This is particularly useful (read: efficient) when you need to perform multiple passes against the data.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. END.

sql  Note: in Oracle8i.The Mutating Table Problem  Database triggers can be attached to the SQL statement and/or the individual row operations on a table.page 55 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . you can use autonomous transactions to relax restrictions associated with queries. it is "mutating". 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. So what are you supposed to do when a row-level operation needs to "touch" that table? mutating.

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

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

rank_depts.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. Statement Level Trigger CREATE OR REPLACE TRIGGER Rank_Sales_Strg AFTER INSERT OR UPDATE OR DELETE ON rank_sales BEGIN rank.add_dept (:new. END. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .pkg All details of the ranking are hidden in the package body. END.sales_amt != NEW.page 58 .dept_id).sales_amt) BEGIN rank. ranking. Doesn't fire unless the sales_amt is actually changed.

END rank. PACKAGE BODY rank IS in_process BOOLEAN := FALSE.The Ranking Package PACKAGE rank IS PROCEDURE add_dept (dept_id_in IN INTEGER). TYPE dept_tabtype IS TABLE OF BOOLEAN INDEX BY BINARY_INTEGER.page 59 . END IF. 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. Table holds indicator that department needs re-ranking. dept_tab dept_tabtype. PROCEDURE rank_depts.

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

 Nested tables ± You want to store large amounts of persistent data in a column. You want to use inside SQL.page 61 . ± You want to use inside SQL.  VARRAYs ± ± ± ± You want to preserve the order in which elements are stored. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . You don't want to have to worry about sparseness. Set of data is relatively small (avoid row chaining).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".

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

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

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

var_name. ± FOR WEAK 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. mismatch. it match the OPEN FOR statement structure. The INTO structure must match in number and datatype to: ± FOR STRONG cursor types.. ± Fetching can continue with a different INTO clause. it match the cursor type data specification. ± The ROWTYPE_MISMATCH exception is raised on failure..Fetching from the Cursor Variable FETCH cursor_var_name INTO record_name..page 73 .  Fetching with cursor variables follows the same rules as those with static cursors.

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

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

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

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

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

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 .page 79 .

page 80 1/21/2011 Copyright 2001 Steven Feuerstein .1 and DBMS_SQL. ± Also supported with "native dynamic SQL" in Oracle8i. you no longer have to write SQL to generate SQL to get your job done. What can you do with Dynamic SQL?  Build ad-hoc query and update applications. ± Very common requirement on the Web. ± Construct powerful DBA utilities. PL/SQL Advanced Techniques .  Execute dynamically-constructed PL/SQL programs. ± One example: implement indirect referencing in PL/SQL.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.  Execute DDL inside PL/SQL programs. ± Available in PL/SQL since Release 2.

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

 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>. ± But this package is very complex. used for DDL.Native Dynamic SQL  Prior to Oracle8i. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . DML and single row fetches.page 82 . ± OPEN FOR <sql string>. and relatively slow (performance did improve significantly as of Oracle8). difficult to use. you would use the DBMS_SQL built-in package to execute dynamic SQL. used for multi-row queries.

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

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

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

± No special syntax needed.pkg PL/SQL Advanced Techniques .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. ± In the following example..page 86 . 1/21/2011 Copyright 2001 Steven Feuerstein health$. the USING clause allows me to pass an object and nested table to an INSERT statement with a variable table name.. pers IN Person. cond. END. :revenue_inhibitors)' USING pers. cond IN preexisting_conditions) IS BEGIN EXECUTE IMMEDIATE 'INSERT INTO ' || tabname (hosp_name) || ' VALUES (:revenue_generator. including objects and collections.

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

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

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

page 90 .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 .

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

CREATE OR REPLACE PROCEDURE updnumval ( col_in IN VARCHAR2.page 92 .CLOSE_CURSOR (cur). val_in IN NUMBER) IS cur PLS_INTEGER := DBMS_SQL.OPEN_CURSOR. DBMS_SQL. END. DBMS_SQL.PARSE (cur. fdbk PLS_INTEGER.EXECUTE (cur).PUT_LINE ('Rows updated: ' || TO_CHAR (fdbk)). ename_in IN emp. updnval1. '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 . BEGIN DBMS_SQL. DBMS_OUTPUT.Updates with Dynamic SQL  Update numeric column for specified employees.NATIVE). fdbk := DBMS_SQL.ename%TYPE.

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

page 94 .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 .

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

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

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

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

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

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

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

COLUMN_VALUE_LONG   First. dumplong. Then you retrieve the column using the special COLUMN_VALUE_LONG variant.DEFINE_COLUMN_LONG ± DBMS_SQL.page 102 .Working with LONG Values  DBMS_SQL provides special procedures so that you can extract values from a LONG column in a table.pkg dumplong. ± 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.tst 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± DBMS_SQL. you define the column as a LONG.

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

page 104 .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. ± Support for RETURNING clause to avoid unnecessary queries. inserts. deletes and fetches. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

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

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

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

Both implementations will still come in handy.page 109 . ± If.NDS or DBMS_SQL: Which is Best?  Dynamic SQL and PL/SQL is very useful.. of course. but DBMS_SQL is hard to use. 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 ..

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

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

page 112 .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 .

± Rule-based subscribers. AQ now offers a publish/subscribe style of messaging between applications. the listen feature and notification capabilities. message propagation. 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. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Key Features of Oracle AQ  Leverage full power of SQL ± Messages are stored in database tables  Database high availability.page 113 .

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 .

0.Oracle AQ Highlights  In 8. 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 .page 115 1/21/2011 Copyright 2001 Steven Feuerstein .

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

payload type. storage clause. optionally waiting for outstanding transactions Adds an ³agent´ as a subscriber 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 117 . whether multiple consumers Drops table if all queues in the table have been stopped Associates queue table with queue. sort column.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.

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

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 .sql 1/21/2011 Copyright 2001 Steven Feuerstein .page 119   aq.  ENQUEUE puts a message into a specified queue. but lots of complexity buried inside the parameters of these procedures. ± Only two procedures.The "operational package": DBMS_AQ  DBMS_AQ is deceptively simple.

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

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

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

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

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

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

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

± Oracle has announced deprecation of LONGs. LOB datatypes are the successor to LONGs.page 127 . video. though they will probably not be actually desupported. they should no longer be used. Images. sounds. etc.  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .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.

 Key programming differences: ± Internal LOBs participate in transactions.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.page 128 . external do not ± External LOBs are read-only from within Oracle 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . improving performance.

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

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

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 .page 131 .The ³LOB locator´ LOB t l sel es [ ll ] t i i t r .

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .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 . ut IRECTORY namespace is global  Syntax: CREATE OR REPLACE DIRECTORY <directory name> AS '<full path to directory>'.

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

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

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

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 . 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.page 139 . call.New DBMS_LOB APIs in 8i  Support for temporary LOBs ± No logging or rollback faster! ± Lifespan: session.

Large Object . ± LOB locator behavior slightly abstruse ± Inability to modify BFILEs directly from within PL/SQL.Summary  LOB support in Oracle is now significantly improved. 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 .

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

triggers in Java Distinct Java & PL/SQL namespaces  But first. functions.. mid-tier. 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. PL/SQL Advanced Techniques .page 142 1/21/2011 Copyright 2001 Steven Feuerstein ....a BRIEF introduction to Java.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.

. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± 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.. ± We just need to keep a firm grip on common sense and stay focused on delivering solutions. fastest.page 143 .

to boot. PL/SQL will still be: ± Faster and more productive than Java for database operations. ± Supported and improved by Oracle -.  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 144 . ± A language in which hundreds of thousands of developers are trained. ± Ubiquitous in thousands of production applications and millions of lines of code.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.

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

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

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

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 .

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

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

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

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

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

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

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

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

± Use the throws clause in your specification.. } 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 . ± So you can pass them as arguments and do anything and everything else you can do with objects.  You must inform users of your method of which exceptions may be thrown.. as in: public static int numBytes (String filename) throws SecurityException. NoSuchFile { .

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .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).page 158 .  Now let's explore how you can put Java to work for you inside PL/SQL programs.

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 .Java Stored Procedures (JSPs) Java applet or app.

JSPs: Some sample uses PL/SQL extender ± For example.page 160 . better file I/O ± RMI callouts. 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 .

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

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

page 163 .java file Java resource file .Upload using ³loadjava´ utility .class 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 .jar file Oracle 8i server Java class Java source Java resource loadjava Example: loadjava loadjava -user scott/tiger -oci8 -resolve datacraft/bill/Hello.

page 164 .Emp(int) return java.) [ return <Ja a t pe fullname> ]'.Hello. .bill..String'. /  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>.Publish  Example (top-level call spec) CREATE OR REPLACE FUNCTION hello_emp (empno_in IN NUMBER) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'datacraft. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques ..lang.

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

String java.math.Timestamp java.REF oracle.sql.ARRAY 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sql.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.sql.lang.sql.Publishing -.STRUCT <named type> oracle.BigDecimal oracle.page 166 .

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

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

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

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

jdbc2.CustomDatum ± oracle.sql.page 171 .sql.STRUCT ± oracle.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.

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 .

/  jspobj.page 173 .Passing object using JPub-generated Java  After generating and uploading classes with JPub.bill.bill.save (datacraft. 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.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Account_t)'.AccountRuntime.

but that package is very limited.   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.page 174 . Let's see how we can make that great Java stuff available from within PL/SQL. Java offers many file-related classes with much greater capabilities.

.  Let's start with something simple. 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. ± The File class offers a length method that returns the number of bytes in a file. ± This is not available through UTL_FILE (though you can get it through DBMS_LOB).Encapsulate Java Classes  You won't generally access native Java methods in your PL/SQL wrapper.

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

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

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

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

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

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

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

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

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

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

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

so file extproc returns results returns results 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .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 .DLL or .page 187 .

page 188 .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.

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

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

number_of_free_clusters BY REFERENCE LONG. 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. sectors_per_cluster OUT PLS_INTEGER. total_number_of_clusters BY REFERENCE LONG. number_of_free_clusters OUT pls_integer. sectors_per_cluster BY REFERENCE LONG.Package body in Oracle 8. bytes_per_sector BY REFERENCE LONG.0 (3/4) CREATE OR REPLACE PACKAGE BODY disk_util AS FUNCTION get_disk_free_space (root_path IN VARCHAR2. END disk_util. RETURN LONG). PL/SQL Advanced Techniques .page 191  All the magic is in the EXTERNAL section 1/21/2011 Copyright 2001 Steven Feuerstein . bytes_per_sector OUT PLS_INTEGER.

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

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 .page 197 .

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

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

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

USER. EXCEPTION WHEN OTHERS THEN ROLLBACK.tst PL/SQL Advanced Techniques . While we're at it. BEGIN INSERT INTO logtab VALUES (code_in.machine.pkg log81*.sp log81.pkg retry.tst retry. rec. let's add some session information. rec. text_in. logger.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. SYSDATE. END. SYSDATE.program ).page 201 . 1/21/2011 Copyright 2001 Steven Feuerstein Avoid interdependencies with the main transaction. USER. END. COMMIT. text_in IN VARCHAR2 ) IS PRAGMA AUTONOMOUS_TRANSACTION.

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

± 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 203 1/21/2011 Copyright 2001 Steven Feuerstein . it ran under the privileges of the account in which the program was defined. whenever you executed a stored program.

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

. each user has own copy of table(s). unless you write code in the package to essentially recreate roles programmatically.Problems with Definer Rights  Deployment & maintenance ± Must install module in all remote databases where needed ± In some databases..page 205 . requiring copy of stored module  Security ± No declarative way to restrict privileges on certain modules in a package -.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.it's all or nothing.

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

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

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

but you want their own directly-granted privileges to determine access.sql whichsch*. authid. ± 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.When to Invoke Invoker Rights  You want to reuse the same code among many users.page 209 . National HQ Check City Statistics New York Schema stolenlives Chicago Schema stolenlives  Especially handy with dynamic SQL.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

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

page 212   1/21/2011 Copyright 2001 Steven Feuerstein . PL/SQL Advanced Techniques .Row-Level Security with DBMS_RLS  Oracle8i offers a new package. 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"). DBMS_RLS. Prior to Oracle8i. The DBMS_RLS package (along with "system contexts") now allow you to do so in a foolproof manner. Row Level Security  The establishment of security policies on (restricted access to) individual rows of a table.

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

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

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

person. information for this retval VARCHAR2(2000). ''' || clause for each type of c_person_id_attr || '''))'. c_person_type_attr).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). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 216 . connection. name_in VARCHAR2) RETURN VARCHAR2 IS l_context VARCHAR2(100) := Extract the context SYS_CONTEXT (c_context. 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 || '''. FUNCTION person_predicate ( schema_in VARCHAR2.

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

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

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

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

a. 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 .page 221 .Achieving PL/SQL Excellence Appendices (a..k.

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

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

page 224 1/21/2011 Copyright 2001 Steven Feuerstein .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. Puts formatted text into the buffer PL/SQL Advanced Techniques .

± You do this by adding lines to the instance parameter file. ± Use a separate entry for each directory (and subdirectory. ± No single or double quotes around directory. no trailing delimiter. 1/21/2011 Copyright 2001 Steven Feuerstein . PL/SQL Advanced Techniques .  Follow these rules to avoid many headaches. utl_file_dir = /tmp utl_file_dir = /accounts/newdev  And don't do either of the following: utl_file_dir = . utl_file_dir = * Allows read & write for any directory.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. there is no subdirectory recursion).

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

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

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

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

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

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

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

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 .

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

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

ISUBMIT and supply the job number.  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. I run calculate_totals immediately and then on a daily basis thereafter. 'calculate_totals. ± In the above example. BEGIN DBMS_JOB. PL/SQL Advanced Techniques . and then the job¶s execution interval (frequency of execution).page 236 1/21/2011 Copyright 2001 Steven Feuerstein .SUBMIT (job#.Submitting a Job DECLARE job# BINARY_INTEGER.  When you submit a job. 'SYSDATE + 1').'. instead of having DBMS_JOB generate one for you. END. Notice that the start time is a DATE expression. while the interval is a string (this is dynamic PL/SQL!)  You can also call DBMS_JOB. SYSDATE. you specify the date on which it should next execute.

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

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

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

END LOOP. DBMS_JOB.page 240 .Other Job Queue Operations  Remove a job from the queue. retaining current job number.ISUBMIT.  Run a job immediately.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .REMOVE (rec.RUN (my_job#). ± 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.job). expjob.  Export jobs from the queue. Remove all jobs for current schema. ± Produces a string that can be used to recreate an existing job in the job queue. ± Uses DBMS_JOB.

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

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

page 243 . ± Do you want it to try 16 times? ± In addition. the job facility will mark your job as broken. Then you can go ahead and submit it. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . it may cause the background processes to fail and no longer run any jobs at all. 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.Error Handling with DBMS_JOB  What if your stored procedure fails? ± After 16 attempts.  To avoid unexpected and unhandled failures of scheduled jobs: ± Always use the RUN built-in to execute your job in a ³test´ mode.

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

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

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

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

± Names can be up to 128 chars long (do not use names beginning with ³ORA$´. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . using a maximum of 4096 bytes. which can be composed of one or more separate packets.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. ± The pipe sends/receives a message. They are reserved for Oracle use).page 248 .

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

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

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

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

timeout IN INTEGER DEFAULT maxwait) RETURN INTEGER.  Then you call UNPACK_MESSAGE to extract individual packets from the message. ± Pipe status of 0 means the message was read successfully. ± You need to know the datatype of packet or check it using NEXT_ITEM_TYPE. PROCEDURE unpack_message (item OUT DATE).page 253 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Specify pipe and number of seconds you will wait before you time out. PROCEDURE unpack_message (item OUT VARCHAR2).  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. PROCEDURE unpack_message (item OUT NUMBER).

'Production data unavailable. END LOOP. pass it on to the IF pipe_status = 0 computation THEN program. analyze_production (SYSDATE.UNPACK_MESSAGE (prod_total). Wait up to N prod_total NUMBER. data not received. LOOP pipe_status := DBMS_PIPE. seconds for the BEGIN next report. PL/SQL Advanced Techniques . DBMS_PIPE. every_n_secs).'). ELSE RAISE_APPLICATION_ERROR ( Stop process if -20000. END IF. PROCEDURE analyze_assembly_data (every_n_secs IN INTEGER) IS pipe_status INTEGER.RECEIVE_MESSAGE ( 'production'. If I got something. END.page 254 1/21/2011 Copyright 2001 Steven Feuerstein .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"!). prod_total).

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. 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.sql dbpipe. you have to make sure that you unpack a packet into the right kind of variable.Unpacking the Message FUNCTION next_item_type RETURN INTEGER. 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.page 255 .

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

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.

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

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

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

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

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 ...

Gets file number part of data block address. Returns execution call stack.page 263 dbver. Returns hash value for string. Gets block number part of data block address.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 . Returns error stack. Parses comma-delimited list to index-by table.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). PL/SQL Advanced Techniques . Returns database version (Oracle8) Executes DDL statement (Oracle8). Recompile INVALID objects in specified schema.pkg dbparm.

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). Returns platform and version of database. Returns TRUE if in parallel server mode.DBMS_UTILITY Module Outline. Resolves name of object into component parts. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Creates data block address from block & file numbers. Returns "current time" down to hundredth of second. cont.page 264 . Parses string object designator into components. Converts list (in index-by-table) of elements into a comma-delimited list (string).

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

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

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

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

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