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

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

Program references package element the first time in each session.page 7 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Package Initialization  The initialization section is a block of code at the end of the package body that is executed once per session. the first time any package element is referenced. ± 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. no Complete request for packaged element.

FUNCTION func RETURN BEGIN END. ± Can have its own exception handling section. PACKAGE BODY pkg IS PROCEDURE proc IS BEGIN END. ± Confirming that package is properly instantiated. In fact. PL/SQL Advanced Techniques . BEGIN END pkg.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. 1/21/2011 Copyright 2001 Steven Feuerstein BEGIN after/outside of any program defined in the pkg. ± Is not required. ± Setting up package data which does not change for the duration of a session.page 8 . most packages you build won't have one.

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

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

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

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

There are two different "compile times": ± 1. IN OUT). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 13 . ± 2. ± Arguments differ only in their mode (IN.How Overloading Works  For two or more modules to be overloaded. When you compile the package or block containing the overloaded code.  Undistinguishing characteristics: ± Functions differ only in their RETURN datatype.  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. ± The programs are of different types: procedure and function. VARCHAR2 is not different enough). OUT. order or datatype family (CHAR vs. When you compile programs that use the overloaded code.

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

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

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

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

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

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

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

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

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

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

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

The Frustrations of Overloading  Watch out! An overloading can compile successfully. I rely on an anchored type (%TYPE) to establish the datatype of the second calc¶s parameter. 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. PROCEDURE calc (comp_id_IN IN company.comp_id%TYPE). END.page 25 1/21/2011 Copyright 2001 Steven Feuerstein . but you might later found out that you cannot actually call any of the overloaded programs. ± When I compile profits.  In the above example. PL/SQL Advanced Techniques .

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

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

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

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

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

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

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

kids child_table_type) NESTED TABLE kids STORE AS kids_ntab.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . 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).page 33 . CREATE TABLE db_family (surname VARCHAR2 (30).

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

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

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

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

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

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

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

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

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

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

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

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

Navigating Through Collections 


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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 46

Using Collections Inside SQL 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 47

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

Barbara Anne Gary Richard Lisa Marie

column_value Barbara Anne Gary Richard Lisa Marie

Barbara Anne Gary Richard Lisa Nadezhka

Using the THE Operator 

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

the.sql

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 49

Using the TABLE and CAST Operators 

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 50

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

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

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

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

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

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

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

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

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

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).  Nested tables ± You want to store large amounts of persistent data in a column.page 61 .Which Collection Type Should I Use?  Index-by tables ± Need to use in both Oracle7 and Oracle8 applications ± Want to take advantage of sparse nature for "intelligent keys".  VARRAYs ± ± ± ± You want to preserve the order in which elements are stored. ± You want to use inside SQL. You want to use inside SQL.

Tips for Using Collections 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 62

Achieving PL/SQL Excellence

Cursor Variables

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 63

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

With Cursor Variables

PGA

Cursor Variable

Cursor Variable

Result Set

Shared Global Area

Cursor Object

Result Set 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

Benefits of Cursor Variables 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 65

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

company_curvar company_curtype;

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

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

FETCH company_curvar INTO company_rec;
Close the cursor variable.

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

PL/SQL Advanced Techniques - page 66

Explicit Cursors and Cursor Variables 

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

Declaring Cursor Types and Variables 

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 68

Strong vs. Weak Cursor Types 

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

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

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

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

Opening with the Cursor Variable
OPEN cursor_name FOR select_statement; 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

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

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

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

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

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

END IF. END.page 76 . BEGIN IF type_in = bydept THEN OPEN retval FOR SELECT empno FROM emp ORDER BY deptno. RETURN retval. / 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. CREATE OR REPLACE PACKAGE BODY allcurs IS FUNCTION open (type_in IN INTEGER) RETURN cv_t IS retval cv_t. ELSIF type_in = bysal THEN OPEN retval FOR SELECT empno FROM emp ORDER BY SAL. END.

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

you can build screens that access data using a cursor variable-based procedural API.page 78 .  Hide Variations in Underlying SQL ± You no longer have to repeat the same code for different cursors.  Strong and Weak Types ± Create REF CURSORs for specific queries. or a more general.  Improve Client-Side Access to Data ± At least in Oracle Developer 2. 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. 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 .

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

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

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

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

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

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

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

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

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

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

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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

page 104 . inserts. deletes and fetches.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. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

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

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

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

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

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

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

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

page 113 . the listen feature and notification capabilities. 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. AQ now offers a publish/subscribe style of messaging between applications. message propagation. ± Rule-based subscribers. 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 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.page 115 1/21/2011 Copyright 2001 Steven Feuerstein .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 .

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 . Underlying database tables and views The queue monitor (background process) ± Set # of processes with the AQ_TM_PROCESSES initialization parameter.page 116 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . the_loc CLOB. str_offset := DBMS_LOB.WRITE(lob_loc => the_loc.com' FOR UPDATE. END IF.INSTR(lob_loc => the_loc. pattern => 'oodb').page 134 . buffer => 'cool'). END. CLOSE hcur. FETCH hcur INTO the_loc. offset => str_offset. BEGIN OPEN hcur.oodb. IF str_offset != 0 THEN DBMS_LOB. 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 INTEGER.

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

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

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

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

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

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

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.page 142 1/21/2011 Copyright 2001 Steven Feuerstein .. 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.a BRIEF introduction to Java. functions. mid-tier..Overview of Java interoperability  Java inside or outside 8i server can call PL/SQL ± Standard JDBC and SQLJ calls with Oracle extensions ± Same Java on client. PL/SQL Advanced Techniques ..

± The end of programming history as we know it? ± The easiest. 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.. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 143 . fastest.Question 1: What is Java?  Could it be. ± We just need to keep a firm grip on common sense and stay focused on delivering solutions..

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

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

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

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

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

you will use a class by instantiating objects from the class and then invoking class methods on the object.   1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Let's build a performance analyzer class to explore these ideas. Usually.page 149 .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. elapsed()). } public void showElapsed (String context) { p.Gstart). public void capture () { Gstart = System.Compare Performance of Methods  Use System.currentTimeMillis() .page 150 .currentTimeMillis() . } } p. System. } public long elapsed () { return (System.java 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .java Tmr.currentTimeMillis().l ("Elapsed time for " + context.Gstart).l ("Elapsed time ".java InFile. } public void showElapsed () { p.currentTimeMillis to calculate elapsed time to nearest thousandth of a second.

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

supertype/"wider" Citizen Person Employee Hourly Worker Salaried Worker subtype/"narrower" War Criminal Person. either as its own class or as any superclass. ± Dynamic polymorphism: form is determined at run-time. ± Static polymorphism: form is chosen at compile-time (PL/SQL overloading).And Now for Some Scary Buzzwords!  Inheritance ± Subclasses inherit methods and variables from extended superclasses.page 152 .  Polymorphism ± An object of a class can have "multiple" forms.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.page 153 . boolean char byte short int long float double  Strings ± A String object is a read-only. String myName. ± Can't do a direct == comparison. these are not objects instantiated from classes.equals(YourName)) foundFamily(). myName = "Steven". 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . if (myName. you are actually allocating a new object. myName = "Feuerstein".Language Basics  Comments // Single line comment /* Block comment */ /** Documentation comment */  Primitive datatypes ± So I lied.

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

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

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

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

page 158 . ± Object oriented development (Java) is very different from procedural coding (PL/SQL).  Now let's explore how you can put Java to work for you inside PL/SQL programs. 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

page 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 diskspace.sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

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

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

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 .

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.    Autonomous Transactions The Invoker Rights Model Row level security 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

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

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

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

it ran under the privileges of the account in which the program was defined. ± This is called the « Invoker Rights Model PL/SQL Advanced Techniques . whenever you executed a stored program.page 203 1/21/2011 Copyright 2001 Steven Feuerstein . ± This is called the « Definer Rights Model  With Oracle8i.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.

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. 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. OE Code Order_Mgt Place Cancel Sam_Sales Close Old Orders  OE Data X  Orders Cannot alter table directly. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

. unless you write code in the package to essentially recreate roles programmatically. ± 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.Problems with Definer Rights  Deployment & maintenance ± Must install module in all remote databases where needed ± In some databases. each user has own copy of table(s).. requiring copy of stored module  Security ± No declarative way to restrict privileges on certain modules in a package -.page 205 .and now you do! 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

.. 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 .. you can execute code owned by another schema.).destroy(. END.page 207 ..FROM accounts WHERE. modify destroy ."Reflection" Capability of Invoker Rights  With invoker rights. code. Central Code schema PACKAGE acct_mgr make AUTHID CURRENT_USER User/Data schema PROCEDURE mng_account IS BEGIN ..acct_mgr...

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

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

HQ Chicago Check City Statistics  New York stolenlives Analyze Pattern stolenlives perpetrators perp. Rely on definer rights to access centralized data from any schema.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.page 210 .

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

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

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . connection.Define the Predicate  A predicate is a string that will be appended to the WHERE clause of the table to which this security policy is associated (see next page).page 216 . ''' || clause for each type of c_person_id_attr || '''))'. FUNCTION person_predicate ( schema_in VARCHAR2. person. 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 || '''. c_person_type_attr). name_in VARCHAR2) RETURN VARCHAR2 IS l_context VARCHAR2(100) := Extract the context SYS_CONTEXT (c_context. information for this retval VARCHAR2(2000).

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

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

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

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

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

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

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

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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

± Perform and commit DML in a separate transaction space from your main transaction. Oracle uses database pipes to parallelize database operations. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 247 . ± Operates outside of database transaction limitations. You can parallelize your own code.  Uses for DBMS_PIPE include: ± Parallelization of program execution.DBMS_PIPE Overview  Allows communication between different Oracle sessions through a pipe in the RDBMS Shared Global Area. ± 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 248 . ± Names can be up to 128 chars long (do not use names beginning with ³ORA$´. which can be composed of one or more separate packets. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . using a maximum of 4096 bytes. ± The pipe sends/receives a message. They are reserved for Oracle use).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.

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

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

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .CREATE_PIPE ( pipename => 'bbs'. ± Implicitly-created pipes are always public. PROCEDURE newpipe IS stat INTEGER. ± Use CREATE_PIPE to create a pipe explicitly. maxpipesize => 20000. BEGIN stat := DBMS_PIPE. private => TRUE). ± Specify TRUE for private argument of CREATE_PIPE.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.page 251 .  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.

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

± Specify pipe and number of seconds you will wait before you time out. ± 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.Receiving and Unpack a Message FUNCTION receive_message (pipename IN VARCHAR2. PROCEDURE unpack_message (item OUT VARCHAR2). 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 253 .  Then you call UNPACK_MESSAGE to extract individual packets from the message. PROCEDURE unpack_message (item OUT DATE). timeout IN INTEGER DEFAULT maxwait) RETURN INTEGER. PROCEDURE unpack_message (item OUT NUMBER).  First you pull the message from the pipe and place it in buffer with RECEIVE_MESSAGE.

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

Unpacking the Message FUNCTION next_item_type RETURN INTEGER. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 255 . you have to make sure that you unpack a packet into the right kind of variable.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. ± 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. 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.

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

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

 The ³kick off´ programs pass their messages to separate pipes.Parallelizing PL/SQL Execution BEGIN kick_off_sales_calc. ± When each program is complete.page 258 1/21/2011 Copyright 2001 Steven Feuerstein . calculate_net_profits.in a muchdecreased elapsed time. it puts a message (perhaps even a value) into the pipe. PL/SQL Advanced Techniques . END.  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. Then net profits can be computed -. wait_for_confirmation. kick_off_exp_calc.

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

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

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

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

Gets file number part of data block address. PL/SQL Advanced Techniques .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 execution call stack.page 263 dbver.DBMS_UTILITY Module Outline ANALYZE_DATABASE ANALYZE_PART_OBJECT Analyze objects in database Runs ANALYZE TABLE or ANALYZE INDEX for each partition of the object (Oracle8). Returns database version (Oracle8) Executes DDL statement (Oracle8). Returns hash value for string. Parses comma-delimited list to index-by table. Returns error stack. Gets block number part of data block address.pkg dbparm. Recompile INVALID objects in specified schema.

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

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

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

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

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

 Possible "Part 1" Types 5 7 8 9 Synonym Procedure Function Package What a chore! All those arguments. object_number OUT NUMBER). part1 OUT VARCHAR2. the way they are attached also follows a complicated syntax.NAME_RESOLVE (name IN VARCHAR2.. schema OUT VARCHAR2.. context IN NUMBER.sp snc.. part1_type OUT NUMBER.Resolving Names of Stored Code  Code names have many components.for encapsulation! showcomp.page 269 . dblink OUT VARCHAR2.. PROCEDURE DBMS_UTILITY.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. see it as an opportunity. part2 OUT VARCHAR2.but don't see it as a problem.

Sign up to vote on this title
UsefulNot useful