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

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

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

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

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

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

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

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

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

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

± The DBMS_OUTPUT. 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.  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. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 15 . 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. In this case.Overload Wherever Possible  Supporting Many Data Combinations ± Apply the same action to different kinds or combinations of data. not Value ± A less common application of overloading.l substitute does an even better job.  Overloading by Type.

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

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

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

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

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

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

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

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

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

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

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

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

Achieving PL/SQL Excellence PL/SQL Collections   Collections are single-dimensioned lists of information. 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 .

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

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

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

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

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

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

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

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

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

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

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

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

pkg psemp. END. emp_tab emp_tabtype. CREATE OR REPLACE PACKAGE BODY psemp IS BEGIN FOR rec IN (SELECT * FROM emp) LOOP emp_tab (rec. 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.Transferring DB Table to Collection CREATE OR REPLACE PACKAGE psemp IS TYPE emp_tabtype IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER. Some questions: ± Why would I put this collection table in a package? ± When is the collection loaded with the data? ± What rows in that collection are utilized? psemp. END LOOP.tst  PL/SQL Advanced Techniques .page 41 . END.empno) := rec.

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

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

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

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

Navigating Through Collections 


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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 46

Using Collections Inside SQL 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 47

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

Barbara Anne Gary Richard Lisa Marie

column_value Barbara Anne Gary Richard Lisa Marie

Barbara Anne Gary Richard Lisa Nadezhka

Using the THE Operator 

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

the.sql

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 49

Using the TABLE and CAST Operators 

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 50

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

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

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

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

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

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

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

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

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

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

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". 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. ± You want to use inside SQL. You want to use inside SQL. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  VARRAYs ± ± ± ± You want to preserve the order in which elements are stored.

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

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

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

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

page 74 .sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . you have to repeat the code for each cursor.When to Use Cursor Variables  Make it easier for calling programs (especially non-PL/SQL programs) to manipulate result sets. ± 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. ± JDBC recognizes cursor variables. but static cursors are more efficient than dynamic SQL and cursor variables are less complicated than DBMS_SQL. Use a single block of code to manipulate multiple queries.  hccursor. since cursor names are "hard coded". ± With explicit cursors.

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

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

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

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

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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

page 93 . DBMS_SQL. end_in). 'hidate'.BIND_VARIABLE (cur.BIND_VARIABLE (cur. BEGIN DBMS_SQL. DBMS_SQL.sp 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . end_in IN DATE.NATIVE). DBMS_SQL. fdbk PLS_INTEGER.EXECUTE (cur). DBMS_OUTPUT.sp updnval3. 'lodate'. start_in IN DATE. fdbk := DBMS_SQL.CLOSE_CURSOR (cur). DBMS_SQL. start_in). updnval2.PUT_LINE ('Rows updated: ' || TO_CHAR (fdbk)).PARSE (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'. CREATE OR REPLACE PROCEDURE updnumval ( col_in IN VARCHAR2. val_in IN NUMBER) IS cur PLS_INTEGER := DBMS_SQL. END.OPEN_CURSOR.

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

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

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

page 97 . raises NO_DATA_FOUND or raises the TOO_MANY_ROWS exception. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± If exact_match is TRUE. 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. numrows := DBMS_SQL. which returns a single row. the first row will still be fetched and available. ± Even if the exception is raised.  Makes it easy to execute and fetch a single row from a query.EXECUTE_AND_FETCH (cur.EXECUTE_AND_FETCH (cur).Using EXECUTE_AND_FETCH FUNCTION execute_and_fetch (cursor_in IN INTEGER. numrows := DBMS_SQL. exact_match IN BOOLEAN DEFAULT FALSE) RETURN INTEGER. TRUE).

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

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

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

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

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

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

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

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

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

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

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

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

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

consistent manner. systems are now heavily reliant on the ability of components to communicate with each other in a dependable.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 .page 111 .

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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  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>'.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").

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

file_exprn) RETURN BFILE. BEGIN INSERT INTO web_graphics VALUES (100015. END.The built-in BFILENAME function  Returns value of datatype BFILE.gif').page 137 . 'prodicon. picture). Spec: FUNCTION BFILENAME(directory_exprn.  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 .

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

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 .page 139 . or transaction  Ability to retrieve LOB ³chunk size´ ± Allows programmer to tune READs and WRITEs  For all internal LOBs ± OPEN & CLOSE allow control over timing. call.New DBMS_LOB APIs in 8i  Support for temporary LOBs ± No logging or rollback faster! ± Lifespan: session.

. ± Complete support in PL/SQL (and other APIs) ± Much better performance and control than with LONGs ± Usable in object types HOT  Some weaknesses.page 140 . COLD 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.Large Object .Summary  LOB support in Oracle is now significantly improved..

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

or server Not covered in this seminar  PL/SQL can call Java inside 8i server ± ± ± ± Command-line tools load Java classes DDL extensions publish Java classes Writing stored procedures.. triggers in Java Distinct Java & PL/SQL namespaces  But first. 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..page 142 1/21/2011 Copyright 2001 Steven Feuerstein ..a BRIEF introduction to Java. functions.. PL/SQL Advanced Techniques .

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

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

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

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

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

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

Using a Class  The main method is handy for providing a built-in test mechanism of your class.   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 . you will use a class by instantiating objects from the class and then invoking class methods on the object. however.

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

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

page 152 . either as its own class or as any superclass.java A Class Hierarchy Management NonManagement Corporation 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . supertype/"wider" Citizen Person Employee Hourly Worker Salaried Worker subtype/"narrower" War Criminal Person. ± 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. ± Dynamic polymorphism: form is determined at run-time.  Polymorphism ± An object of a class can have "multiple" forms.

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

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

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

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

Differences Between Java & PL/SQL  Exceptions are objects derived directly or indirectly from the Exception class. ± Use the throws clause in your specification.. NoSuchFile { ..  You must inform users of your method of which exceptions may be thrown. } 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.page 157 . as in: public static int numBytes (String filename) throws SecurityException.

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

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

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

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

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

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

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

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

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

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

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

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

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

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.CustomDatum ± oracle.jdbc2.SQLData 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 171 .STRUCT ± oracle.sql.

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

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

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

 Let's start with something simple.Encapsulate Java Classes  You won't generally access native Java methods in your PL/SQL wrapper..page 175 . ± Instead build a static method that instantiates a Java object from the class and then invokes the relevant method against that object. ± This is not available through UTL_FILE (though you can get it through DBMS_LOB).. ± 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 .

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

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

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

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

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

sql. // starting with 0 String laborType = (String)(attribs[0]).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. System. // Access individual attributes by array index. 1/21/2011 Copyright 2001 Steven Feuerstein UnionBuster. } } Extract individual attribute values from the array.SQLException { // Get the attributes of the labor_source object. BigDecimal hourly_rate = (BigDecimal)(attribs[1]).java passobj. throws java.page 181 .out.println ( "Pay " + laborType + " $" + hourly_rate + " per hour"). Object[] attribs = e.getAttributes(). public class UnionBuster { Obtain attributes of public static void wageStrategy (STRUCT e) the Oracle object.

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

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

Error Handling with Java-PL/SQL  Java offers a very similar. ± And also spew out the entire Java error stack! (at least through 8. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Exceptions are objects instantiated from the Exception class or a subclass of it. ± Instead of raising and handling. getErrorCode() and getMessage() to obtain information about the error thrown.page 184 .5).sql.  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. you "throw" and "catch". but more robust error handling mechanism than PL/SQL.SQLException.1. ± Use two methods.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

.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 -.and now you do! 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques ..it's all or nothing. ± 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. unless you write code in the package to essentially recreate roles programmatically.page 205 .

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

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

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

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. ± 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 whichsch*. but you want their own directly-granted privileges to determine access. authid.page 209 .When to Invoke Invoker Rights  You want to reuse the same code among many users.

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

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

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

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

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

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

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). information for this retval VARCHAR2(2000). c_person_type_attr). BEGIN IF l_context = 'DOCTOR' THEN retval := 'home_clinic_id IN (SELECT home_clinic_id FROM doctor We need a different string WHERE doctor_id = SYS_CONTEXT (''' || to modify the WHERE c_context || '''. person. connection. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 216 . ''' || clause for each type of c_person_id_attr || '''))'. FUNCTION person_predicate ( schema_in VARCHAR2. name_in VARCHAR2) RETURN VARCHAR2 IS l_context VARCHAR2(100) := Extract the context SYS_CONTEXT (c_context.

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

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

Context Information for "SWALLACE": Type: DOCTOR Doctor sees only her ID: 1060 patients.Chris Silva .Veva Silva .IL 1/21/2011 Copyright 2001 Steven Feuerstein Patient sees only himself. PL/SQL Advanced Techniques .page 219 .IL VSILVA . Predicate: home_clinic_id IN (SELECT home_clinic_id FROM doctor WHERE doctor_id = SYS_CONTEXT ('patient_restriction'.IL Context Information for "CSILVA": Type: PATIENT ID: Predicate: schema_name = 'CSILVA' Patients Visible to "CSILVA": CSILVA .Chris Silva . 'person_id')) Patients Visible to "SWALLACE": CSILVA .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. February.page 220 ....... Jump out of your rut .. March.and play a new tune with PL/SQL! 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .Take Full Advantage of PL/SQL! January.  ± You learn what you need to get the job done... April. and you use only what you know. May..

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

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

0. random access to contents). ± Limitations on files you can access (no mapped files. copy.5..page 223 . when it jumps to 32K.   But you can read lines from a file and write lines to a file. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± Maximum of 1023 bytes per line (read or write) until Oracle 8.. A "version 1" (fairly primitive) utility.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. no use of environmental variables).

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

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

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

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

FILE_TYPE.FOPEN ('c:\temp'. 'test. END.GET_LINE (fid. BEGIN fid := UTL_FILE.5 and above. ± You might want to build your own GET_LINE which handles the exception and returns an EOF Boolean status flag.txt'.Reading from a File DECLARE fid UTL_FILE. 'R').FCLOSE (fid). getnext. myline). UTL_FILE.page 228 . ± In Oracle8 Release 8.sp 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .   Can only read from a file opened with the "R" mode. the ceiling is raised to 32K. UTL_FILE. 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.0.

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

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

± They all share a common SQLCODE of 1. EXCEPTION. EXCEPTION. EXCEPTION. EXCEPTION. ± UTL_FILE-named exceptions in other cases.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. ± NO_DATA_FOUND when you try to read past the end of the file. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  You have to take special care to trap and handle the named exceptions. EXCEPTION. EXCEPTION.page 231 .  UTL_FILE relies on a combination of user-defined exceptions and STANDARD exceptions to communicate errors.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

page 247 . Oracle uses database pipes to parallelize database operations.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). ± Operates outside of database transaction limitations.  Uses for DBMS_PIPE include: ± Parallelization of program execution. ± Interface PL/SQL-database activities with operating system functions and programs written in other languages. ± Perform and commit DML in a separate transaction space from your main transaction. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . You can parallelize your own code.

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

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

DBMS_PIPE Module Outline Module Name CREATE_PIPE Description Creates a PUBLIC or PRIVATE pipe. making it a candidate for removal with a LRU algorithm. REMOVE_PIPE RESET_BUFFER Removes a pipe explicitly created via CREATE_PIPE. PURGE Empties the contents of a pipe into your local buffer freeing it for removal. UNIQUE_SESSION_NAME Returns name that is unique among all sessions in the database. NEXT_ITEM_TYPE Returns the datatype of the next item in the piped message. RECEIVE_MESSAGE Receives a message from pipe and copies to local buffer.page 250 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . PACK_MESSAGE Packs an item into the message buffer for your session. 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful