Achieving PL/SQL Excellence

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 1

Objective & Outline 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 2

Software Used in Training 

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 3

Achieving PL/SQL Excellence

Building with PL/SQL Packages 
 

Overview Initialization section Overloading

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 4

What is a Package? 

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 5

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

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

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

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

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

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

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

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

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

so much as providing different ways of requesting the same activity.PUT_LINE procedure illustrates this technique -and the PL/Vision p.  Overloading by Type. ± The DBMS_OUTPUT.page 15 .l substitute does an even better job. not Value ± A less common application of overloading. the overloading does not provide a single name for different activities.Overload Wherever Possible  Supporting Many Data Combinations ± Apply the same action to different kinds or combinations of data. 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 . You use the type of data and not its value to determine which of the overloaded programs should be executed. In this case.  Fitting the Program to the User ± To make your code as useful as possible.

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

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

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

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

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

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

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

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

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

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

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

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

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

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. PL/SQL Advanced Techniques .  Emulate bi-directional cursors. Build hash tables (custom indexing structures). Avoid mutating table errors in database triggers. Improve query performance by avoiding joins.page 29     1/21/2011 Copyright 2001 Steven Feuerstein .

147. this broad range allows you to employ the row number as an intelligent key. ± 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. Valid row numbers range: -2.page 30 .647 to 2.147. DECLARE TYPE inmem_emp_t IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER.Index-By Tables TYPE <table_type> IS TABLE OF <datatype> INDEX BY BINARY_INTEGER.483. emp_copy inmem_emp_t. ± Homogeneous » Data in each row has the same structure.483. ± Sparse » Data does not have to be stored in consecutive rows of information.  Characteristics of an index-by table: ± Unbounded » Practically speaking. Instead.

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

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

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 . CREATE TABLE db_family (surname VARCHAR2 (30). kids child_table_type) NESTED TABLE kids STORE AS kids_ntab. For ORACLE's use only db_family surname kids BOLZ BOND Eric Thomas Max Richard Barbara Anne Gary Richard Lisa Marie ntdemo.

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

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

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

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

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

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

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

tst  PL/SQL Advanced Techniques .page 41 . CREATE OR REPLACE PACKAGE BODY psemp IS BEGIN FOR rec IN (SELECT * FROM emp) LOOP emp_tab (rec.pkg psemp. 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. emp_tab emp_tabtype.Transferring DB Table to Collection CREATE OR REPLACE PACKAGE psemp IS TYPE emp_tabtype IS TABLE OF emp%ROWTYPE INDEX BY BINARY_INTEGER. END. Initialization section of package 1/21/2011 Copyright 2001 Steven Feuerstein  This package moves the entire contents of the emp table into its corresponding collection.empno) := rec. END. END LOOP.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tips for Using Collections 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 62

Achieving PL/SQL Excellence

Cursor Variables

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 63

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

With Cursor Variables

PGA

Cursor Variable

Cursor Variable

Result Set

Shared Global Area

Cursor Object

Result Set 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

Benefits of Cursor Variables 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 65

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

company_curvar company_curtype;

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

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

FETCH company_curvar INTO company_rec;
Close the cursor variable.

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

PL/SQL Advanced Techniques - page 66

Explicit Cursors and Cursor Variables 

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

Declaring Cursor Types and Variables 

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 68

Strong vs. Weak Cursor Types 

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

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

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

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

Opening with the Cursor Variable
OPEN cursor_name FOR select_statement; 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

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

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

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

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

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

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

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

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

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

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

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

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

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

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

end_in IN DATE.  Execute a stored procedure. EXCEPTION WHEN OTHERS THEN pl ('Compile Error "' || SQLERRM || '" on: ' || v_str).page 85 .. 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. end_in. END. col_in IN VARCHAR2. BEGIN v_str := 'BEGIN ' || pkg_in || '.' || name_in || '. END. start_in IN DATE.'. PROCEDURE runprog (pkg_in IN VARCHAR2. start_in. CREATE OR REPLACE PROCEDURE updnumval ( tab_in IN VARCHAR2.Other Execute Immediate Examples  Perform an update. END. name_in IN VARCHAR2) IS v_str VARCHAR2 (100). Pass in bind variables with USING clause... 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .

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

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

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

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

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 .

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

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

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

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

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

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

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

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

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

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

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

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

 Before PL/SQL8.Describing Cursor Columns PROCEDURE DBMS_SQL.DESCRIBE_COLUMNS (c IN INTEGER.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. ± The record TYPE is also defined in DBMS_SQL.page 105 .DESC_TAB). it was not possible to determine the datatypes of the columns defined in a cursor. desc_t OUT DBMS_SQL. ± Now you can call the DBMS_SQL. col_cnt OUT INTEGER.

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

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

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

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

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

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

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 .

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

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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/ 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. scanned_card_image BFILE ).page 136 ... CREATE TYPE Business_card_t AS OBJECT ( name Name_t. image BFILE)..Using BFILE datatype in DDL  In a table. addresses Address_tab_t.

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

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

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

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

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

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

. fastest.page 143 . ± We just need to keep a firm grip on common sense and stay focused on delivering solutions. 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.Question 1: What is Java?  Could it be.

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

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

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

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

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

however.   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.page 149 . Usually. Let's build a performance analyzer class to explore these ideas.Using a Class  The main method is handy for providing a built-in test mechanism of your class.

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

.page 151 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques .  Abstract class ± The class can contain members and methods.  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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Creating your own external procedure 

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 193

1. Identify/create external routine 


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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 194

2. Create the Oracle library 

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

PL/SQL Advanced Techniques - page 195

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

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

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

1/21/2011 Copyright 2001 Steven Feuerstein

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

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

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

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

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

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

± This is called the « Definer Rights Model  With Oracle8i.page 203 1/21/2011 Copyright 2001 Steven Feuerstein . 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. whenever you executed a stored program.The Invoker Rights Model  Prior to Oracle8i. 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 .

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

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

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

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

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

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

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

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

page 212   1/21/2011 Copyright 2001 Steven Feuerstein . The DBMS_RLS package (along with "system contexts") now allow you to do so in a foolproof manner. DBMS_RLS.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. Prior to Oracle8i. you could achieve this only partially through the use of views. with which to implement automated row-level security (also referred to as "fine grained access control").

the system context is a named set of attributevalue pairs global to your session.page 213 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . their context information is set properly.  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.  DBMS_RLS ± Use programs in DBMS_RLS to associate your security policies with tables.  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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

sql dbpipe.page 255 . 1/21/2011 Copyright 2001 Steven Feuerstein PL/SQL Advanced Techniques . 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. you have to make sure that you unpack a packet into the right kind of variable.Unpacking the Message FUNCTION next_item_type RETURN INTEGER. Either: ± You know the datatype and therefore can ³hard-code´ the correct variable into the call to UNPACK_MESSAGE. ± Or you use the built-in NEXT_ITEM_TYPE to tell you in advance the datatype of the next packet in the message and take appropriate action.tst  Since a message can be composed of packets of different datatypes.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful