Achieving PL/SQL Excellence

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 1

Objective & Outline 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 2

Software Used in Training 

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 3

Achieving PL/SQL Excellence

Building with PL/SQL Packages 
 

Overview Initialization section Overloading

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 4

What is a Package? 

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 5

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

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

In fact.page 8 . PACKAGE BODY pkg IS PROCEDURE proc IS BEGIN END. PL/SQL Advanced Techniques .  Useful for: ± Performing complex setting of default or initial values.Package Initialization Structure  The initialization section: ± Is defined after and outside of any programs in the package. ± Can have its own exception handling section. BEGIN END pkg. FUNCTION func RETURN BEGIN END. most packages you build won't have one. ± Is not required. ± Confirming that package is properly instantiated. 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.

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

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

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

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

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

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

page 15 .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. ± The DBMS_OUTPUT. you may construct different versions of the ³same´ program which correspond to different patterns of use. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . In this case.  Overloading by Type. the overloading does not provide a single name for different activities.  Fitting the Program to the User ± To make your code as useful as possible.PUT_LINE procedure illustrates this technique -and the PL/Vision p. 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.l substitute does an even better job.

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

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

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

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

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

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

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

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

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

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. ± When I compile profits. but you might later found out that you cannot actually call any of the overloaded programs.comp_id%TYPE). PROCEDURE calc (comp_id_IN IN company.  In the above example. PL/SQL does not sense a conflict with above overloading even though comp_id is a numeric column. END.page 25 1/21/2011 Copyright 2001 Steven Feuerstein . PL/SQL Advanced Techniques . PACKAGE profits IS PROCEDURE calc (comp_id_IN IN NUMBER).

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

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

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. Oracle8 and above) 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . Three types of collections: ± Index-by tables (Oracle7 only.page 28 .

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

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

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

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

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

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

kids child_va_type).page 35 . 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.Variable Arrays CREATE OR REPLACE TYPE child_va_type IS VARRAY (8) OF VARCHAR2 (30).sql 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tips for Using Collections 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 62

Achieving PL/SQL Excellence

Cursor Variables

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 63

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

With Cursor Variables

PGA

Cursor Variable

Cursor Variable

Result Set

Shared Global Area

Cursor Object

Result Set 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

Benefits of Cursor Variables 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 65

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

company_curvar company_curtype;

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

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

FETCH company_curvar INTO company_rec;
Close the cursor variable.

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

PL/SQL Advanced Techniques - page 66

Explicit Cursors and Cursor Variables 

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

Declaring Cursor Types and Variables 

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 68

Strong vs. Weak Cursor Types 

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

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

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

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

Opening with the Cursor Variable
OPEN cursor_name FOR select_statement; 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 71 . .  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.Opening with Strong Cursor Types DECLARE TYPE emp_curtype IS REF CURSOR RETURN emp%ROWTYPE. emp_curvar emp_curtype. Match Needed BEGIN OPEN emp_curvar FOR SELECT * from emp.. END. a cursor or a programmer-defined record.

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

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

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

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

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

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

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

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

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

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

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

including objects. {IN | OUT | IN OUT] bind argument]. define_variables].EXECUTE IMMEDIATE EXECUTE IMMEDIATE sql-string [INTO {define_variable[.... | record }] [USING {IN | OUT | IN OUT] bind argument [. collections and records.].. PL/SQL Advanced Techniques .  Use this statement to execute any dynamic SQL statement (including a PL/SQL block) except for multi-row queries. 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.page 83   1/21/2011 Copyright 2001 Steven Feuerstein .

. WHERE clause...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. sch IN VARCHAR2 := NULL) RETURN INTEGER IS Specify schema. table and retval INTEGER.page 84 . IF tabCount ('citizens'. END.000.sf compare with: tabcount. RETURN retval..PUT_LINE ( 'Not the best health care system in the world. 'insured = ''NO''') > 40. and not much of a democracy either!'). 1/21/2011 Copyright 2001 Steven Feuerstein tabcount81.' || tab || ' WHERE ' || NVL (whr. '1=1') INTO retval. END IF.sf PL/SQL Advanced Techniques . whr IN VARCHAR2 := NULL. BEGIN EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || NVL (sch. USER) || '.

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

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

val VARCHAR2(32767). DBMS_OUTPUT. 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. showcol. cv cv_type. whr IN VARCHAR2 := NULL) IS TYPE cv_type IS REF CURSOR. '1 = 1'). variable syntax! EXIT WHEN cv%NOTFOUND. LOOP Familiar cursor FETCH cv INTO val. ndsutil.pkg 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . CREATE OR REPLACE PROCEDURE showcol ( tab IN VARCHAR2.sp END. ± Here is a simple utility the displays the values of any date. CLOSE cv. number or string column in any table.page 87 . col IN VARCHAR2.PUT_LINE (val). END LOOP.

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

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

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

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

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

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

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

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

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

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

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

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

 LAST_SQL_FUNCTION_CODE ± Returns SQL function code of cursor.  LAST_ROW_COUNT ± Returns the cumulative count of rows fetched from the cursor.  IS_OPEN ± Is the cursor already open?  LAST_ERROR_POSITION ± Returns relative column position in cursor of text causing error condition.page 101 . ± 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. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  LAST_ROW_ID ± Returns the ROWID of last row processed.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

page 139 . that can mean less I/O » Trigger will not fire until CLOSE » Indexes will not update until CLOSE ± ISOPEN 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . call. 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.New DBMS_LOB APIs in 8i  Support for temporary LOBs ± No logging or rollback faster! ± Lifespan: session.

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

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

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 . 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.. functions. mid-tier. triggers in Java Distinct Java & PL/SQL namespaces  But first..a BRIEF introduction to Java.

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

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. it is very unlikely and totally unthinkable for years to come. to boot.  1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . ± A language in which hundreds of thousands of developers are trained.and very aggressively. ± Supported and improved by Oracle -.Question 2: Will Java Replace PL/SQL?  While that scenario is certainly possible.page 144 .

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

Oh. except the "special" main method.page 146 . } }  No members..println ("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. public class Hello { public static void main (String[] args) { System. ± Used to test or run stand-alone a class. CREATE OR REPLACE PROCEDURE hello IS BEGIN DBMS_OUTPUT.PUT_LINE ('Hello world!'). END.out.

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

long Playoffs.println (TheGlobalMonster). paying its" + " Chief Executive Officer " + CEOCompensation. } public String toString () { return name + " is a transnational entity with " + layoffs + " laid-off employees. public Corporation ( String Pname. } public static void main (String[] args) { // A very scary company Corporation TheGlobalMonster = new Corporation ( "Northrup-Ford-Mattel-Yahoo-ATT". long PceoComp) { name = Pname. 50000000).out.out. System. 5000000. CEOCompensation = PceoComp. }} 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. layoffs = Playoffs. long CEOCompensation.java Advanced Techniques .page 162 PL/SQL . Entry points must be public static in most cases Classes may call other classes Avoid GUI calls     person.Create Java class(es) class Corporation extends Person { long layoffs.

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

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

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

Publishing -.REF oracle.sql.BigDecimal oracle.STRUCT <named type> oracle.sql.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.Timestamp java.math.String java.page 166 .lang.sql.

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

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

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

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

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

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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

 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.page 186 . ± Must be a shared object library on Unix or a dynamically linked library (DLL) on Windows.Achieving PL/SQL Excellence External Procedures  An external procedure is a 3GL routine that can serve as the ³body´ of a PL/SQL function. procedure.

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

External procedures: Sample uses      Send email Invoke operating system command Invoke custom or legacy application Call C runtime library function Perform admin tasks email.sql diskspace.page 188 .sql 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. create an Oracle8 ³library´: CREATE OR REPLACE LIBRARY nt_kernel AS 'c:\winnt\system32\kernel32. this function returns: » » » » » sectors per cluster bytes per sector number of free clusters total number of clusters ³return code´ indicating success or failure  First.page 189 .dll ± For given drive letter. / 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .dll'.

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

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

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

Creating your own external procedure 

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 193

1. Identify/create external routine 


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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 194

2. Create the Oracle library 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 195

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

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

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

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

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

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

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

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

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

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

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

page 207 . END."Reflection" Capability of Invoker Rights  With invoker rights... modify destroy .). 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 . yet have all references to data structures "reflect back" into your own schema...acct_mgr. code..destroy(. you can execute code owned by another schema..FROM accounts WHERE.

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

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.When to Invoke Invoker Rights  You want to reuse the same code among many users. but you want their own directly-granted privileges to determine access. ± Share a program that uses dynamic SQL (whether DBMS_SQL or the new native implementation) and you end up taking the most unexpected DDL and DML detours. authid.page 209 .sql whichsch*.

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

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

DBMS_RLS. Prior to Oracle8i.page 212   1/21/2011 Copyright 2001 Steven Feuerstein . 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. you could achieve this only partially through the use of views.Row-Level Security with DBMS_RLS  Oracle8i offers a new package. PL/SQL Advanced Techniques . Row Level Security  The establishment of security policies on (restricted access to) individual rows of a table.

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

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

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

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

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

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

Chris Silva .Queries Transparently Filtered  What you see is determined automatically by who you are.IL VSILVA .IL 1/21/2011 Copyright 2001 Steven Feuerstein Patient sees only himself. 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 . Context Information for "SWALLACE": Type: DOCTOR Doctor sees only her ID: 1060 patients.Veva Silva .page 219 .Chris Silva . 'person_id')) Patients Visible to "SWALLACE": CSILVA . PL/SQL Advanced Techniques .

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

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

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

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

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

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 = .  Follow these rules to avoid many headaches. ± You do this by adding lines to the instance parameter file. PL/SQL Advanced Techniques .page 225 Allows read & write for current directory. no trailing delimiter. ± Use a separate entry for each directory (and subdirectory. there is no subdirectory recursion). utl_file_dir = * Allows read & write for any directory.Authorizing Directory Access  Oracle requires you to list explicitly those directories you wish to be able to read/write with UTL_FILE.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .sql dbpipe.Unpacking the Message FUNCTION next_item_type RETURN INTEGER. 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. 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. ± 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.page 255 .

± The CEO is decidedly unhappy about the delay. total office expenses and total compensation. In order to do so I must first compute total sales. you can do the same for your application if: ± You have multiple CPUs available. 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. 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .page 256 .  Suppose I want to calculate my net profit. ± These programs each take 15 minutes. but are not dependent on each other.Parallelizing Your Code with Pipes  Oracle uses DBMS_PIPE to improve RDBMS performance.

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 .

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

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

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

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

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

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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful