Oracle PL/SQL Programming, 6th Edition

Book description

Considered the best Oracle PL/SQL programming guide by the Oracle community, this definitive guide is precisely what you need to make the most of Oracle’s powerful procedural language. The sixth edition describes the features and capabilities of PL/SQL up through Oracle Database 12c Release 1.

Hundreds of thousands of PL/SQL developers have benefited from this book over the last twenty years; this edition continues that tradition. With extensive code examples and a lively sense of humor, this book explains language fundamentals, explores advanced coding techniques, and offers best practices to help you solve real-world problems.

  • Get PL/SQL programs up and running quickly, with clear instructions for executing, tracing, testing, debugging, and managing code
  • Understand new 12.1 features, including the ACCESSIBLE_BY clause, WITH FUNCTION and UDF pragma, BEQUEATH CURRENT_USER for views, and new conditional compilation directives
  • Take advantage of extensive code samples, from easy-to-follow examples to reusable packaged utilities
  • Optimize PL/SQL performance with features like the function result cache and Oracle utilities such as PL/Scope and the PL/SQL hierarchical profiler
  • Build modular, easy-to-maintain PL/SQL applications using packages, procedures, functions, and triggers

Publisher resources

View/Submit Errata

Table of contents

  1. Dedication
  2. A Note Regarding Supplemental Files
  3. Preface
    1. Objectives of This Book
    2. Structure of This Book
      1. About the Contents
      2. What This Book Does Not Cover
    3. Conventions Used in This Book
    4. Which Platform or Version?
    5. About the Code
    6. Using Code Examples
    7. Safari® Books Online
    8. How to Contact Us
    9. Acknowledgments
  4. I. Programming in PL/SQL
    1. 1. Introduction to PL/SQL
      1. What Is PL/SQL?
      2. The Origins of PL/SQL
        1. The Early Years of PL/SQL
        2. Improved Application Portability
        3. Improved Execution Authority and Transaction Integrity
        4. Humble Beginnings, Steady Improvement
      3. So This Is PL/SQL
        1. Integration with SQL
        2. Control and Conditional Logic
        3. When Things Go Wrong
      4. About PL/SQL Versions
        1. Oracle Database 12c New PL/SQL Features
          1. More PL/SQL-only datatypes cross PL/SQL-to-SQL interface
          2. ACCESSIBLE_BY clause
          3. Implicit statement results
          4. BEQUEATH CURRENT_USER views
          5. Grant roles to program units
          6. New conditional compilation directives
          7. Optimizing function execution in SQL
          8. Using %ROWTYPE with invisible columns
          9. FETCH FIRST clause and BULK COLLECT
          10. The UTL_CALL_STACK package
      5. Resources for PL/SQL Developers
        1. The O’Reilly PL/SQL Series
        2. PL/SQL on the Internet
      6. Some Words of Advice
        1. Don’t Be in Such a Hurry!
        2. Don’t Be Afraid to Ask for Help
        3. Take a Creative, Even Radical Approach
    2. 2. Creating and Running PL/SQL Code
      1. Navigating the Database
      2. Creating and Editing Source Code
      3. SQL*Plus
        1. Starting Up SQL*Plus
        2. Running a SQL Statement
        3. Running a PL/SQL Program
        4. Running a Script
        5. What Is the “Current Directory”?
        6. Other SQL*Plus Tasks
          1. Setting your preferences
          2. Saving output to a file
          3. Exiting SQL*Plus
          4. Editing a statement
          5. Loading your own custom environment automatically on startup
        7. Error Handling in SQL*Plus
        8. Why You Will Love and Hate SQL*Plus
      4. Performing Essential PL/SQL Tasks
        1. Creating a Stored Program
        2. Executing a Stored Program
        3. Showing Stored Programs
        4. Managing Grants and Synonyms for Stored Programs
        5. Dropping a Stored Program
        6. Hiding the Source Code of a Stored Program
      5. Editing Environments for PL/SQL
      6. Calling PL/SQL from Other Languages
        1. C: Using Oracle’s Precompiler (Pro*C)
        2. Java: Using JDBC
        3. Perl: Using Perl DBI and DBD::Oracle
        4. PHP: Using Oracle Extensions
        5. PL/SQL Server Pages
        6. And Where Else?
    3. 3. Language Fundamentals
      1. PL/SQL Block Structure
        1. Anonymous Blocks
        2. Named Blocks
        3. Nested Blocks
        4. Scope
        5. Qualify All References to Variables and Columns in SQL Statements
          1. Improve readability
          2. Avoid bugs through qualifiers
        6. Visibility
          1. Visible identifiers
          2. Qualified identifiers
          3. Qualifying identifier names with module names
          4. Nested programs
      2. The PL/SQL Character Set
      3. Identifiers
        1. Reserved Words
          1. Reserved words
          2. Identifiers from STANDARD package
          3. How to avoid using reserved words
        2. Whitespace and Keywords
      4. Literals
        1. NULLs
        2. Embedding Single Quotes Inside a Literal String
        3. Numeric Literals
        4. Boolean Literals
      5. The Semicolon Delimiter
      6. Comments
        1. Single-Line Comment Syntax
        2. Multiline Comment Syntax
      7. The PRAGMA Keyword
      8. Labels
  5. II. PL/SQL Program Structure
    1. 4. Conditional and Sequential Control
      1. IF Statements
        1. The IF-THEN Combination
        2. The IF-THEN-ELSE Combination
        3. The IF-THEN-ELSIF Combination
        4. Avoiding IF Syntax Gotchas
        5. Nested IF Statements
        6. Short-Circuit Evaluation
      2. CASE Statements and Expressions
        1. Simple CASE Statements
        2. Searched CASE Statements
        3. Nested CASE Statements
        4. CASE Expressions
      3. The GOTO Statement
      4. The NULL Statement
        1. Improving Program Readability
        2. Using NULL After a Label
    2. 5. Iterative Processing with Loops
      1. Loop Basics
        1. Examples of Different Loops
        2. Structure of PL/SQL Loops
      2. The Simple Loop
        1. Terminating a Simple Loop: EXIT and EXIT WHEN
        2. Emulating a REPEAT UNTIL Loop
        3. The Intentionally Infinite Loop
      3. The WHILE Loop
      4. The Numeric FOR Loop
        1. Rules for Numeric FOR Loops
        2. Examples of Numeric FOR Loops
        3. Handling Nontrivial Increments
      5. The Cursor FOR Loop
        1. Example of Cursor FOR Loops
      6. Loop Labels
      7. The CONTINUE Statement
      8. Tips for Iterative Processing
        1. Use Understandable Names for Loop Indexes
        2. The Proper Way to Say Goodbye
        3. Obtaining Information About FOR Loop Execution
        4. SQL Statement as Loop
    3. 6. Exception Handlers
      1. Exception-Handling Concepts and Terminology
      2. Defining Exceptions
        1. Declaring Named Exceptions
        2. Associating Exception Names with Error Codes
          1. Using EXCEPTION_INIT
          2. Recommended uses of EXCEPTION_INIT
        3. About Named System Exceptions
        4. Scope of an Exception
      3. Raising Exceptions
        1. The RAISE Statement
        2. Using RAISE_APPLICATION_ERROR
      4. Handling Exceptions
        1. Built-in Error Functions
          1. More on DBMS_UTILITY.FORMAT_ERROR_BACKTRACE
          2. Just the line number, please
          3. Useful applications of SQLERRM
        2. Combining Multiple Exceptions in a Single Handler
        3. Unhandled Exceptions
        4. Propagation of Unhandled Exceptions
          1. Losing exception information
          2. Examples of exception propagation
        5. Continuing Past Exceptions
        6. Writing WHEN OTHERS Handling Code
      5. Building an Effective Error Management Architecture
        1. Decide on Your Error Management Strategy
        2. Standardize Handling of Different Types of Exceptions
          1. Deliberate exceptions
          2. Unfortunate and unexpected exceptions
          3. How to benefit from this categorization
        3. Organize Use of Application-Specific Error Codes
        4. Use Standardized Error Management Programs
        5. Work with Your Own Exception “Objects”
        6. Create Standard Templates for Common Error Handling
      6. Making the Most of PL/SQL Error Management
  6. III. PL/SQL Program Data
    1. 7. Working with Program Data
      1. Naming Your Program Data
      2. Overview of PL/SQL Datatypes
        1. Character Data
        2. Numbers
        3. Dates, Timestamps, and Intervals
        4. Booleans
        5. Binary Data
        6. ROWIDs
        7. REF CURSORs
        8. Internet Datatypes
        9. “Any” Datatypes
        10. User-Defined Datatypes
      3. Declaring Program Data
        1. Declaring a Variable
        2. Declaring Constants
        3. The NOT NULL Clause
        4. Anchored Declarations
        5. Anchoring to Cursors and Tables
        6. Benefits of Anchored Declarations
          1. Synchronization with database columns
          2. Normalization of local variables
        7. Anchoring to NOT NULL Datatypes
      4. Programmer-Defined Subtypes
      5. Conversion Between Datatypes
        1. Implicit Data Conversion
          1. Limitations of implicit conversion
          2. Drawbacks of implicit conversion
        2. Explicit Datatype Conversion
          1. The CHARTOROWID function
          2. The CAST function
          3. The CONVERT function
          4. The HEXTORAW function
          5. The RAWTOHEX function
          6. The ROWIDTOCHAR function
    2. 8. Strings
      1. String Datatypes
        1. The VARCHAR2 Datatype
        2. The CHAR Datatype
        3. String Subtypes
      2. Working with Strings
        1. Specifying String Constants
        2. Using Nonprintable Characters
        3. Concatenating Strings
        4. Dealing with Case
          1. Forcing a string to all upper- or lowercase
          2. Making comparisons case insensitive
          3. Case insensitivity and indexes
          4. Capitalizing each word in a string
        5. Traditional Searching, Extracting, and Replacing
        6. Padding
        7. Trimming
        8. Regular Expression Searching, Extracting, and Replacing
          1. Detecting a pattern
          2. Locating a pattern
          3. Extracting text matching a pattern
          4. Counting regular expression matches
          5. Replacing text
          6. Groking greediness
          7. Learning more about regular expressions
        9. Working with Empty Strings
        10. Mixing CHAR and VARCHAR2 Values
          1. Database-to-variable conversion
          2. Variable-to-database conversion
          3. String comparisons
          4. Character functions and CHAR arguments
      3. String Function Quick Reference
    3. 9. Numbers
      1. Numeric Datatypes
        1. The NUMBER Type
        2. The PLS_INTEGER Type
        3. The BINARY_INTEGER Type
        4. The SIMPLE_INTEGER Type
        5. The BINARY_FLOAT and BINARY_DOUBLE Types
        6. The SIMPLE_FLOAT and SIMPLE_DOUBLE Types
        7. Numeric Subtypes
      2. Number Conversions
        1. The TO_NUMBER Function
          1. Using TO_NUMBER with no format
          2. Using TO_NUMBER with a format model
          3. Passing NLS settings to TO_NUMBER
        2. The TO_CHAR Function
          1. Using TO_CHAR with no format
          2. Using TO_CHAR with a format model
          3. The V format element
          4. Rounding when converting numbers to character strings
          5. Dealing with spaces when converting numbers to character strings
          6. Passing NLS settings to TO_CHAR
        3. The CAST Function
        4. Implicit Conversions
      3. Numeric Operators
      4. Numeric Functions
        1. Rounding and Truncation Functions
        2. Trigonometric Functions
        3. Numeric Function Quick Reference
    4. 10. Dates and Timestamps
      1. Datetime Datatypes
        1. Declaring Datetime Variables
        2. Choosing a Datetime Datatype
      2. Getting the Current Date and Time
      3. Interval Datatypes
        1. Declaring INTERVAL Variables
        2. When to Use INTERVALs
          1. Finding the difference between two datetime values
          2. Designating periods of time
      4. Datetime Conversions
        1. From Strings to Datetimes
        2. From Datetimes to Strings
        3. Working with Time Zones
        4. Requiring a Format Mask to Match Exactly
        5. Easing Up on Exact Matches
        6. Interpreting Two-Digit Years in a Sliding Window
        7. Converting Time Zones to Character Strings
        8. Padding Output with Fill Mode
      5. Date and Timestamp Literals
      6. Interval Conversions
        1. Converting from Numbers to Intervals
        2. Converting Strings to Intervals
        3. Formatting Intervals for Display
      7. Interval Literals
      8. CAST and EXTRACT
        1. The CAST Function
        2. The EXTRACT Function
      9. Datetime Arithmetic
        1. Date Arithmetic with Intervals and Datetimes
        2. Date Arithmetic with DATE Datatypes
        3. Computing the Interval Between Two Datetimes
        4. Mixing DATEs and TIMESTAMPs
        5. Adding and Subtracting Intervals
        6. Multiplying and Dividing Intervals
        7. Using Unconstrained INTERVAL Types
      10. Date/Time Function Quick Reference
    5. 11. Records
      1. Records in PL/SQL
        1. Benefits of Using Records
          1. Data abstraction
          2. Aggregate operations
          3. Leaner, cleaner code
        2. Declaring Records
        3. Programmer-Defined Records
          1. Declaring programmer-defined record TYPEs
          2. Declaring the record
          3. Examples of programmer-defined record declarations
        4. Working with Records
          1. Record-level operations
          2. Field-level operations
          3. Field-level operations with nested records
          4. Field-level operations with package-based records
        5. Comparing Records
        6. Trigger Pseudorecords
          1. %ROWTYPE and invisible columns (Oracle Database 12c)
    6. 12. Collections
      1. Collections Overview
        1. Collections Concepts and Terminology
        2. Types of Collections
        3. Collection Examples
          1. Using an associative array
          2. Using a nested table
          3. Using a VARRAY
        4. Where You Can Use Collections
          1. Collections as components of a record
          2. Collections as program parameters
          3. Collection as datatype of a function’s return value
          4. Collection as “columns” in a database table
          5. Collections as attributes of an object type
        5. Choosing a Collection Type
      2. Collection Methods (Built-ins)
        1. The COUNT Method
          1. Boundary considerations
          2. Exceptions possible
        2. The DELETE Method
          1. Boundary considerations
          2. Exceptions possible
        3. The EXISTS Method
          1. Boundary considerations
          2. Exceptions possible
        4. The EXTEND Method
          1. Boundary considerations
          2. Exceptions possible
        5. The FIRST and LAST Methods
          1. Boundary considerations
          2. Exceptions possible
        6. The LIMIT Method
          1. Boundary considerations
          2. Exceptions possible
        7. The PRIOR and NEXT Methods
          1. Boundary considerations
          2. Exceptions possible
        8. The TRIM Method
          1. Boundary considerations
          2. Exceptions possible
      3. Working with Collections
        1. Declaring Collection Types
          1. Declaring an associative array collection type
          2. Declaring a nested table or VARRAY
          3. Changing a nested table or VARRAY characteristics
        2. Declaring and Initializing Collection Variables
          1. Initializing implicitly during direct assignment
          2. Initializing implicitly via FETCH
          3. VARRAY integration
        3. Populating Collections with Data
          1. Using the assignment operator
          2. What index values can I use?
          3. Aggregate assignments
          4. Assigning rows from a relational table
          5. Advantage of nonsequential population of collection
        4. Accessing Data Inside a Collection
        5. Using String-Indexed Collections
          1. Simplifying algorithmic logic with string indexes
          2. Emulating primary keys and unique indexes
          3. Performance of string-indexed collections
          4. Other examples of string-indexed collections
        6. Collections of Complex Datatypes
          1. Collections of records
          2. Collections of objects and other complex types
        7. Multilevel Collections
          1. Unnamed multilevel collections: Emulation of multidimensional arrays
          2. Exploring the multdim API
          3. Extending string_tracker with multilevel collections
          4. How deeply can I nest collections?
        8. Working with Collections in SQL
          1. The CAST pseudofunction
          2. The COLLECT pseudofunction
          3. The MULTISET pseudofunction
          4. The TABLE pseudofunction
          5. Sorting contents of collections
      4. Nested Table Multiset Operations
        1. Testing Equality and Membership of Nested Tables
        2. Checking for Membership of an Element in a Nested Table
        3. Performing High-Level Set Operations
        4. Handling Duplicates in a Nested Table
      5. Maintaining Schema-Level Collections
        1. Necessary Privileges
        2. Collections and the Data Dictionary
    7. 13. Miscellaneous Datatypes
      1. The BOOLEAN Datatype
      2. The RAW Datatype
      3. The UROWID and ROWID Datatypes
        1. Getting ROWIDs
        2. Using ROWIDs
      4. The LOB Datatypes
      5. Working with LOBs
        1. Understanding LOB Locators
        2. Empty Versus NULL LOBs
        3. Writing into a LOB
        4. Reading from a LOB
        5. BFILEs Are Different
          1. Creating a BFILE locator
          2. Accessing BFILEs
          3. Using BFILEs to load LOB columns
        6. SecureFiles Versus BasicFiles
          1. Deduplication
          2. Compression
          3. Encryption
        7. Temporary LOBs
          1. Creating a temporary LOB
          2. Freeing a temporary LOB
          3. Checking to see whether a LOB is temporary
          4. Managing temporary LOBs
        8. Native LOB Operations
          1. SQL semantics
          2. SQL semantics may yield temporary LOBs
          3. Performance impact of using SQL semantics
        9. LOB Conversion Functions
      6. Predefined Object Types
        1. The XMLType Type
        2. The URI Types
        3. The Any Types
  7. IV. SQL in PL/SQL
    1. 14. DML and Transaction Management
      1. DML in PL/SQL
        1. A Quick Introduction to DML
          1. The INSERT statement
          2. The UPDATE statement
          3. The DELETE statement
          4. The MERGE statement
        2. Cursor Attributes for DML Operations
        3. RETURNING Information from DML Statements
        4. DML and Exception Handling
        5. DML and Records
          1. Record-based inserts
          2. Record-based updates
          3. Using records with the RETURNING clause
          4. Restrictions on record-based inserts and updates
      2. Transaction Management
        1. The COMMIT Statement
        2. The ROLLBACK Statement
        3. The SAVEPOINT Statement
        4. The SET TRANSACTION Statement
        5. The LOCK TABLE Statement
      3. Autonomous Transactions
        1. Defining Autonomous Transactions
        2. Rules and Restrictions on Autonomous Transactions
        3. Transaction Visibility
        4. When to Use Autonomous Transactions
        5. Building an Autonomous Logging Mechanism
    2. 15. Data Retrieval
      1. Cursor Basics
        1. Some Data Retrieval Terms
        2. Typical Query Operations
        3. Introduction to Cursor Attributes
          1. The %FOUND attribute
          2. The %NOTFOUND attribute
          3. The %ROWCOUNT attribute
          4. The %ISOPEN attribute
          5. The %BULK_ROWCOUNT attribute
          6. The %BULK_EXCEPTIONS attribute
        4. Referencing PL/SQL Variables in a Cursor
        5. Choosing Between Explicit and Implicit Cursors
      2. Working with Implicit Cursors
        1. Implicit Cursor Examples
        2. Error Handling with Implicit Cursors
        3. Implicit SQL Cursor Attributes
      3. Working with Explicit Cursors
        1. Declaring Explicit Cursors
          1. Naming your cursor
          2. Declaring cursors in packages
        2. Opening Explicit Cursors
        3. Fetching from Explicit Cursors
          1. Examples of explicit cursors
          2. Fetching past the last row
        4. Column Aliases in Explicit Cursors
        5. Closing Explicit Cursors
        6. Explicit Cursor Attributes
        7. Cursor Parameters
          1. Generalizing cursors with parameters
          2. Opening cursors with parameters
          3. Scope of cursor parameters
          4. Cursor parameter modes
          5. Default values for parameters
      4. SELECT...FOR UPDATE
        1. Releasing Locks with COMMIT
        2. The WHERE CURRENT OF Clause
      5. Cursor Variables and REF CURSORs
        1. Why Use Cursor Variables?
        2. Similarities to Static Cursors
        3. Declaring REF CURSOR Types
        4. Declaring Cursor Variables
        5. Opening Cursor Variables
        6. Fetching from Cursor Variables
          1. Handling the ROWTYPE_MISMATCH exception
        7. Rules for Cursor Variables
          1. Compile-time rowtype matching rules
          2. Runtime rowtype matching rules
          3. Cursor variable aliases
          4. Scope of cursor object
        8. Passing Cursor Variables as Arguments
          1. Identifying the REF CURSOR type
          2. Setting the parameter mode
        9. Cursor Variable Restrictions
      6. Cursor Expressions
        1. Using Cursor Expressions
          1. Retrieving a subquery as a column
          2. Implementing a streaming function with the CURSOR expression
        2. Restrictions on Cursor Expressions
    3. 16. Dynamic SQL and Dynamic PL/SQL
      1. NDS Statements
        1. The EXECUTE IMMEDIATE Statement
        2. The OPEN FOR Statement
          1. FETCH into variables or records
          2. The USING clause in OPEN FOR
        3. About the Four Dynamic SQL Methods
          1. Method 1
          2. Method 2
          3. Method 3
          4. Method 4
      2. Binding Variables
        1. Argument Modes
        2. Duplicate Placeholders
        3. Passing NULL Values
      3. Working with Objects and Collections
      4. Dynamic PL/SQL
        1. Build Dynamic PL/SQL Blocks
        2. Replace Repetitive Code with Dynamic Blocks
      5. Recommendations for NDS
        1. Use Invoker Rights for Shared Programs
        2. Anticipate and Handle Dynamic Errors
        3. Use Binding Rather than Concatenation
        4. Minimize the Dangers of Code Injection
          1. Restrict privileges tightly on user schemas
          2. Use bind variables whenever possible
          3. Check dynamic text for dangerous text
          4. Use DBMS_ASSERT to validate inputs
      6. When to Use DBMS_SQL
        1. Obtain Information About Query Columns
        2. Meeting Method 4 Dynamic SQL Requirements
          1. The “in table” procedural interface
          2. Steps for intab construction
          3. Constructing the SELECT
          4. Defining the cursor structure
          5. Retrieving and displaying data
        3. Minimizing Parsing of Dynamic Cursors
        4. Oracle Database 11g New Dynamic SQL Features
          1. DBMS_SQL.TO_REFCURSOR function
          2. DBMS_SQL.TO_CURSOR function
        5. Enhanced Security for DBMS_SQL
          1. Unpredictable cursor numbers
          2. Denial of access to DBMS_SQL when bad cursor number is used (ORA-24971)
          3. Rejection of DBMS_SQL operation when effective user changes (ORA-24970)
  8. V. PL/SQL Application Construction
    1. 17. Procedures, Functions, and Parameters
      1. Modular Code
      2. Procedures
        1. Calling a Procedure
        2. The Procedure Header
        3. The Procedure Body
        4. The END Label
        5. The RETURN Statement
      3. Functions
        1. Structure of a Function
        2. The RETURN Datatype
        3. The END Label
        4. Calling a Function
        5. Functions Without Parameters
        6. The Function Header
        7. The Function Body
        8. The RETURN Statement
          1. RETURN any valid expression
          2. Multiple RETURNs
          3. RETURN as the last executable statement
      4. Parameters
        1. Defining Parameters
        2. Actual and Formal Parameters
        3. Parameter Modes
          1. IN mode
          2. OUT mode
          3. IN OUT mode
        4. Explicit Association of Actual and Formal Parameters in PL/SQL
          1. Positional notation
          2. Named notation
          3. Benefits of named notation
        5. The NOCOPY Parameter Mode Qualifier
        6. Default Values
      5. Local or Nested Modules
        1. Benefits of Local Modularization
          1. Reducing code volume
          2. Improving readability
        2. Scope of Local Modules
        3. Sprucing Up Your Code with Nested Subprograms
      6. Subprogram Overloading
        1. Benefits of Overloading
          1. Supporting many data combinations
        2. Restrictions on Overloading
        3. Overloading with Numeric Types
      7. Forward Declarations
      8. Advanced Topics
        1. Calling Your Function from Inside SQL
          1. Requirements for calling functions in SQL
          2. Restrictions on user-defined functions in SQL
          3. Read consistency and user-defined functions
          4. Defining PL/SQL subprograms in SQL statements (12.1 and higher)
        2. Table Functions
          1. Calling a function in a FROM clause
          2. Passing table function results with a cursor variable
          3. Creating a streaming function
          4. Creating a pipelined function
          5. Enabling a function for parallel execution
        3. Deterministic Functions
        4. Implicit Cursor Results (Oracle Database 12c)
      9. Go Forth and Modularize!
    2. 18. Packages
      1. Why Packages?
        1. Demonstrating the Power of the Package
        2. Some Package-Related Concepts
        3. Diagramming Privacy
      2. Rules for Building Packages
        1. The Package Specification
        2. The Package Body
        3. Initializing Packages
          1. Execute complex initialization logic
          2. Cache static session information
          3. Avoid side effects when initializing
          4. When initialization fails
      3. Rules for Calling Packaged Elements
      4. Working with Package Data
        1. Global Within a Single Oracle Session
        2. Global Public Data
        3. Packaged Cursors
          1. Declaring packaged cursors
          2. Working with packaged cursors
        4. Serializable Packages
      5. When to Use Packages
        1. Encapsulate Data Access
        2. Avoid Hardcoding Literals
        3. Improve Usability of Built-in Features
        4. Group Together Logically Related Functionality
        5. Cache Static Session Data
      6. Packages and Object Types
    3. 19. Triggers
      1. DML Triggers
        1. DML Trigger Concepts
          1. DML trigger scripts
          2. Transaction participation
        2. Creating a DML Trigger
          1. The WHEN clause
          2. Working with NEW and OLD pseudo-records
          3. Determining the DML action within a trigger
        3. DML Trigger Example: No Cheating Allowed!
          1. Applying the WHEN clause
          2. Using pseudo-records to fine-tune trigger execution
        4. Multiple Triggers of the Same Type
        5. Who Follows Whom
        6. Mutating Table Errors
        7. Compound Triggers: Putting It All in One Place
          1. Just like a package
          2. Not just like a package
          3. Compound following
      2. DDL Triggers
        1. Creating a DDL Trigger
        2. Available Events
        3. Available Attributes
        4. Working with Events and Attributes
          1. What column did I touch?
          2. Lists returned by attribute functions
        5. Dropping the Undroppable
        6. The INSTEAD OF CREATE Trigger
      3. Database Event Triggers
        1. Creating a Database Event Trigger
        2. The STARTUP Trigger
        3. The SHUTDOWN Trigger
        4. The LOGON Trigger
        5. The LOGOFF Trigger
        6. The SERVERERROR Trigger
          1. SERVERERROR examples
          2. Central error handler
      4. INSTEAD OF Triggers
        1. Creating an INSTEAD OF Trigger
        2. The INSTEAD OF INSERT Trigger
        3. The INSTEAD OF UPDATE Trigger
        4. The INSTEAD OF DELETE Trigger
        5. Populating the Tables
        6. INSTEAD OF Triggers on Nested Tables
      5. AFTER SUSPEND Triggers
        1. Setting Up for the AFTER SUSPEND Trigger
        2. Looking at the Actual Trigger
        3. The ORA_SPACE_ERROR_INFO Function
        4. The DBMS_RESUMABLE Package
        5. Trapped Multiple Times
        6. To Fix or Not to Fix?
      6. Maintaining Triggers
        1. Disabling, Enabling, and Dropping Triggers
        2. Creating Disabled Triggers
        3. Viewing Triggers
        4. Checking the Validity of Triggers
    4. 20. Managing PL/SQL Code
      1. Managing Code in the Database
        1. Overview of Data Dictionary Views
        2. Display Information About Stored Objects
        3. Display and Search Source Code
        4. Use Program Size to Determine Pinning Requirements
        5. Obtain Properties of Stored Code
        6. Analyze and Modify Trigger State Through Views
        7. Analyze Argument Information
        8. Analyze Identifier Usage (Oracle Database 11g’s PL/Scope)
      2. Managing Dependencies and Recompiling Code
        1. Analyzing Dependencies with Data Dictionary Views
        2. Fine-Grained Dependency (Oracle Database 11g)
        3. Remote Dependencies
        4. Limitations of Oracle’s Remote Invocation Model
        5. Recompiling Invalid Program Units
          1. Automatic runtime compilation
          2. ALTER...COMPILE recompilation
          3. Schema-level recompilation
      3. Compile-Time Warnings
        1. A Quick Example
        2. Enabling Compile-Time Warnings
        3. Some Handy Warnings
          1. PLW-05000: Mismatch in NOCOPY qualification between specification and body
          2. PLW-05001: Previous use of ‘string’ (at line string) conflicts with this use
          3. PLW-05003: Same actual parameter (string and string) at IN and NOCOPY may have side effects
          4. PLW-05004: Identifier string is also declared in STANDARD or is a SQL built-in
          5. PLW-05005: Function string returns without value at line string
          6. PLW-06002: Unreachable code
          7. PLW-07203: Parameter string may benefit from use of the NOCOPY compiler hint
          8. PLW-07204: Conversion away from column type may result in suboptimal query plan
          9. PLW-06009: Procedure string OTHERS handler does not end in RAISE or RAISE_APPLICATION_ERROR
      4. Testing PL/SQL Programs
        1. Typical, Tawdry Testing Techniques
        2. General Advice for Testing PL/SQL Code
        3. Automated Testing Options for PL/SQL
      5. Tracing PL/SQL Execution
        1. DBMS_UTILITY.FORMAT_CALL_STACK
        2. UTL_CALL_STACK (Oracle Database 12c)
        3. DBMS_APPLICATION_INFO
        4. Tracing with opp_trace
        5. The DBMS_TRACE Facility
          1. Installing DBMS_TRACE
          2. DBMS_TRACE programs
          3. Control trace file contents
          4. Pause and resume the trace process
          5. Format of collected data
      6. Debugging PL/SQL Programs
        1. The Wrong Way to Debug
          1. Disorganized debugging
          2. Irrational debugging
        2. Debugging Tips and Strategies
          1. Use a source code debugger
          2. Gather data
          3. Remain logical at all times
          4. Analyze instead of trying
          5. Take breaks, and ask for help
          6. Change and test one area of code at a time
      7. Using Whitelisting to Control Access to Program Units
      8. Protecting Stored Code
        1. Restrictions on and Limitations of Wrapping
        2. Using the Wrap Executable
        3. Dynamic Wrapping with DBMS_DDL
        4. Guidelines for Working with Wrapped Code
      9. Introduction to Edition-Based Redefinition (Oracle Database 11g Release 2)
    5. 21. Optimizing PL/SQL Performance
      1. Tools to Assist in Optimization
        1. Analyzing Memory Usage
        2. Identifying Bottlenecks in PL/SQL Code
          1. DBMS_PROFILER
          2. The hierarchical profiler
        3. Calculating Elapsed Time
        4. Choosing the Fastest Program
        5. Avoiding Infinite Loops
        6. Performance-Related Warnings
      2. The Optimizing Compiler
        1. Insights on How the Optimizer Works
        2. Runtime Optimization of Fetch Loops
      3. Data Caching Techniques
        1. Package-Based Caching
          1. When to use package-based caching
          2. A simple example of package-based caching
          3. Caching table contents in a package
          4. Just-in-time caching of table data
        2. Deterministic Function Caching
        3. THe Function Result Cache (Oracle Database 11g)
          1. Enabling the function result cache
          2. The RELIES_ON clause (deprecated in 11.2)
          3. Function result cache example: A deterministic function
          4. Function result cache example: Querying data from a table
          5. Function result cache example: Caching a collection
          6. When to use the function result cache
          7. When not to use the function result cache
          8. Useful details of function result cache behavior
          9. Managing the function result cache
          10. Fine-grained dependencies in 11.2 and higher
          11. The virtual private database and function result caching
        4. Caching Summary
      4. Bulk Processing for Repeated SQL Statement Execution
        1. High-Speed Querying with BULK COLLECT
          1. Limiting rows retrieved with BULK COLLECT
          2. Bulk fetching of multiple columns
          3. Using the RETURNING clause with bulk operations
        2. High-Speed DML with FORALL
          1. Syntax of the FORALL statement
          2. FORALL examples
          3. Cursor attributes for FORALL
          4. ROLLBACK behavior with FORALL
          5. Continuing past exceptions with SAVE EXCEPTIONS
          6. Driving FORALL with nonsequential arrays
            1. INDICES OF example
            2. VALUES OF example
      5. Improving Performance with Pipelined Table Functions
        1. Replacing Row-Based Inserts with Pipelined Function-Based Loads
          1. A pipelined function implementation
          2. Loading from a pipelined function
          3. Tuning pipelined functions with array fetches
          4. Exploiting parallel pipelined functions for ultimate performance
          5. Enabling parallel pipelined function execution
        2. Tuning Merge Operations with Pipelined Functions
          1. Row-based PL/SQL merge processing
          2. Using pipelined functions for set-based MERGE
        3. Asynchronous Data Unloading with Parallel Pipelined Functions
          1. A typical data-extract program
          2. A parallel-enabled pipelined function unloader
        4. Performance Implications of Partitioning and Streaming Clauses in Parallel Pipelined Functions
          1. Relative performance of partitioning and streaming combinations
          2. Partitioning with skewed data
        5. Pipelined Functions and the Cost-Based Optimizer
          1. Cardinality heuristics for pipelined table functions
          2. Using optimizer dynamic sampling for pipelined functions
          3. Providing cardinality statistics to the optimizer
          4. Extensible Optimizer and pipelined function cardinality
        6. Tuning Complex Data Loads with Pipelined Functions
          1. One source, two targets
          2. Piping multiple record types from pipelined functions
          3. Using object-relational features
          4. A multitype pipelined function
          5. Querying a multitype pipelined function
          6. Loading multiple tables from a multitype pipelined function
          7. An alternative multitype method
        7. A Final Word on Pipelined Functions
      6. Specialized Optimization Techniques
        1. Using the NOCOPY Parameter Mode Hint
          1. Restrictions on NOCOPY
          2. Performance benefits of NOCOPY
          3. The downside of NOCOPY
        2. Using the Right Datatype
          1. Avoid implicit conversions
          2. Use PLS_INTEGER for intensive integer computations
          3. Use BINARY_FLOAT or BINARY_DOUBLE for floating-point arithmetic
        3. Optimizing Function Performance in SQL (12.1 and higher)
      7. Stepping Back for the Big Picture on Performance
    6. 22. I/O and PL/SQL
      1. Displaying Information
        1. Enabling DBMS_OUTPUT
        2. Write Lines to the Buffer
        3. Read the Contents of the Buffer
      2. Reading and Writing Files
        1. The UTL_FILE_DIR Parameter
          1. Setting up directories
          2. Specifying file locations when opening files
        2. Working with Oracle Directories
        3. Open Files
        4. Is the File Already Open?
        5. Close Files
        6. Read from Files
          1. GET_LINE exceptions
          2. Handy encapsulation for GET_LINE
        7. Write to Files
          1. Writing formatted text to file
        8. Copy Files
        9. Delete Files
        10. Rename and Move Files
        11. Retrieve File Attributes
      3. Sending Email
        1. Oracle Prerequisites
        2. Configuring Network Security
        3. Send a Short (32,767 Bytes or Less) Plain-Text Message
        4. Include “Friendly” Names in Email Addresses
        5. Send a Plain-Text Message of Arbitrary Length
        6. Send a Message with a Short (32,767 Bytes or Less) Attachment
        7. Send a Small File (32,767 Bytes or Less) as an Attachment
        8. Attach a File of Arbitrary Size
      4. Working with Web-Based Data (HTTP)
        1. Retrieve a Web Page in “Pieces”
        2. Retrieve a Web Page into a LOB
        3. Authenticate Using HTTP Username/Password
        4. Retrieve an SSL-Encrypted Web Page (via HTTPS)
        5. Submit Data to a Web Page via GET or POST
        6. Disable Cookies or Make Cookies Persistent
        7. Retrieve Data from an FTP Server
        8. Use a Proxy Server
      5. Other Types of I/O Available in PL/SQL
        1. Database Pipes, Queues, and Alerts
        2. TCP Sockets
        3. Oracle’s Built-in Web Server
  9. VI. Advanced PL/SQL Topics
    1. 23. Application Security and PL/SQL
      1. Security Overview
      2. Encryption
        1. Key Length
        2. Algorithms
        3. Padding and Chaining
        4. The DBMS_CRYPTO Package
          1. Algorithms
          2. Padding and chaining
        5. Encrypting Data
        6. Encrypting LOBs
        7. SecureFiles
        8. Decrypting Data
        9. Performing Key Generation
        10. Performing Key Management
          1. A single key for the database
          2. A single key for each row
          3. A combined approach
        11. Cryptographic Hashing
        12. Using Message Authentication Codes
        13. Using Transparent Data Encryption
        14. Transparent Tablespace Encryption
      3. Row-Level Security
        1. Why Learn About RLS?
        2. A Simple RLS Example
        3. Static Versus Dynamic Policies
          1. Shared static policies
          2. Context-sensitive policies
          3. Shared context-sensitive policies
        4. Using Column-Sensitive RLS
        5. RLS Debugging
          1. Interpreting errors
          2. Performing direct path operations
          3. Viewing SQL statements
      4. Application Contexts
        1. Using Application Contexts
        2. Security in Contexts
        3. Contexts as Predicates in RLS
        4. Identifying Nondatabase Users
      5. Fine-Grained Auditing
        1. Why Learn About FGA?
        2. A Simple FGA Example
        3. Access How Many Columns?
        4. Checking the Audit Trail
        5. Using Bind Variables
        6. Using Handler Modules
    2. 24. PL/SQL Architecture
      1. DIANA
      2. How Oracle Executes PL/SQL Code
        1. An Example
        2. Compiler Limits
      3. The Default Packages of PL/SQL
      4. Execution Authority Models
        1. The Definer Rights Model
          1. Advantages of definer rights
          2. Disadvantages of definer rights
            1. Where’d my table go?
            2. How do I maintain all that code?
            3. Dynamic SQL and definer rights
            4. Privilege escalation and SQL injection
        2. The Invoker Rights Model
          1. Invoker rights syntax
          2. Rules and restrictions on invoker rights
        3. Combining Rights Models
        4. Granting Roles to PL/SQL Program Units (Oracle Database 12c)
        5. “Who Invoked Me?” Functions (Oracle Database 12c)
        6. BEQUEATH CURRENT_USER for Views (Oracle Database 12c)
        7. Constraining Invoker Rights Privileges (Oracle Database 12c)
      5. Conditional Compilation
        1. Examples of Conditional Compilation
          1. Use application package constants in $IF directive
          2. Toggle tracing through conditional compilation flags
        2. The Inquiry Directive
          1. The DBMS_DB_VERSION package
          2. Setting compilation environment parameters
          3. Referencing unit name and line number
          4. Using the PLSQL_CCFLAGS parameter
        3. The $IF Directive
        4. The $ERROR Directive
        5. Synchronizing Code with Packaged Constants
        6. Program-Specific Settings with Inquiry Directives
        7. Working with Postprocessed Code
      6. PL/SQL and Database Instance Memory
        1. The SGA, PGA, and UGA
          1. System global area (SGA)
          2. Process global area (PGA)
          3. User global area (UGA)
        2. Cursors, Memory, and More
        3. Tips on Reducing Memory Use
          1. Statement sharing
          2. Bind variables
          3. Packaging to improve memory use and performance
          4. Large collections in PL/SQL
          5. BULK COLLECT...LIMIT operations
          6. Preservation of state
        4. What to Do If You Run Out of Memory
      7. Native Compilation
        1. When to Run in Interpreted Mode
        2. When to Go Native
        3. Native Compilation and Database Release
      8. What You Need to Know
    3. 25. Globalization and Localization in PL/SQL
      1. Overview and Terminology
      2. Unicode Primer
        1. National Character Set Datatypes
        2. Character Encoding
        3. Globalization Support Parameters
        4. Unicode Functions
          1. ASCIISTR
          2. COMPOSE
          3. DECOMPOSE
          4. INSTR/INSTRB/INSTRC/INSTR2/INSTR4
          5. LENGTH/LENGTHB/LENGTHC/LENGTH2/LENGTH4
          6. SUBSTR/SUBSTRB/SUBSTRC/SUBSTR2/SUBSTR4
          7. UNISTR
      3. Character Semantics
      4. String Sort Order
        1. Binary Sort
        2. Monolingual Sort
        3. Multilingual Sort
      5. Multilingual Information Retrieval
        1. IR and PL/SQL
      6. Date/Time
        1. Timestamp Datatypes
        2. Date/Time Formatting
      7. Currency Conversion
      8. Globalization Development Kit for PL/SQL
        1. UTL_118N Utility Package
        2. UTL_LMS Error-Handling Package
        3. GDK Implementation Options
          1. Method 1: Locale buttons
          2. Method 2: User administration
          3. Method 3: Hybrid
    4. 26. Object-Oriented Aspects of PL/SQL
      1. Introduction to Oracle’s Object Features
      2. Object Types by Example
        1. Creating a Base Type
        2. Creating a Subtype
        3. Methods
        4. Invoking Supertype Methods in Oracle Database 11g and Later
        5. Storing, Retrieving, and Using Persistent Objects
          1. Object identity
          2. The VALUE function
          3. The TREAT function
        6. Evolution and Creation
        7. Back to Pointers?
          1. Using REFs
          2. The UTL_REF package
          3. REFs and type hierarchies
          4. Dangling REFs
        8. Generic Data: The ANY Types
          1. Preview: What ANYDATA is not
          2. Dealing with ANYDATA
          3. Creating a transient type
        9. I Can Do It Myself
        10. Comparing Objects
          1. Attribute-level comparison
          2. The MAP method
          3. The ORDER method
          4. Additional comparison recommendations
      3. Object Views
        1. A Sample Relational System
        2. Object View with a Collection Attribute
        3. Object Subview
        4. Object View with Inverse Relationship
        5. INSTEAD OF Triggers
          1. The case against
          2. The case for
          3. The bigger question
        6. Differences Between Object Views and Object Tables
          1. OID uniqueness
          2. “Storeability” of physical versus virtual REFs
          3. REFs to nonunique OIDs
      4. Maintaining Object Types and Object Views
        1. Data Dictionary
        2. Privileges
          1. The EXECUTE privilege
          2. The UNDER privilege
          3. The DEBUG privilege
          4. The DML privileges
      5. Concluding Thoughts from a (Mostly) Relational Developer
  10. 27. Calling Java from PL/SQL
    1. Oracle and Java
    2. Getting Ready to Use Java in Oracle
      1. Installing Java
      2. Building and Compiling Your Java Code
      3. Setting Permissions for Java Development and Execution
        1. Java security for Oracle through 8.1.5
        2. Java security for Oracle from 8.1.6
    3. A Simple Demonstration
      1. Finding the Java Functionality
      2. Building a Custom Java Class
      3. Compiling and Loading into Oracle
      4. Building a PL/SQL Wrapper
      5. Deleting Files from PL/SQL
    4. Using loadjava
    5. Using dropjava
    6. Managing Java in the Database
      1. The Java Namespace in Oracle
      2. Examining Loaded Java Elements
    7. Using DBMS_JAVA
      1. LONGNAME: Converting Java Long Names
      2. GET_, SET_, and RESET_COMPILER_OPTION: Getting and Setting (a Few) Compiler Options
      3. SET_OUTPUT: Enabling Output from Java
      4. EXPORT_SOURCE, EXPORT_RESOURCE, and EXPORT_CLASS: Exporting Schema Objects
    8. Publishing and Using Java in PL/SQL
      1. Call Specs
      2. Some Rules for Call Specs
      3. Mapping Datatypes
      4. Calling a Java Method in SQL
      5. Exception Handling with Java
      6. Extending File I/O Capabilities
        1. Polishing up the delete method
        2. Obtaining directory contents
      7. Other Examples
  11. 28. External Procedures
    1. Introduction to External Procedures
      1. Example: Invoking an Operating System Command
      2. Architecture of External Procedures
    2. Oracle Net Configuration
      1. Specifying the Listener Configuration
      2. Security Characteristics of the Configuration
    3. Setting Up Multithreaded Mode
    4. Creating an Oracle Library
    5. Writing the Call Specification
      1. The Call Spec: Overall Syntax
      2. Parameter Mapping: The Example Revisited
      3. Parameter Mapping: The Full Story
      4. More Syntax: The PARAMETERS Clause
      5. PARAMETERS Properties
        1. The INDICATOR property
        2. The LENGTH property
        3. The MAXLEN property
        4. The CHARSETID and CHARSETFORM properties
    6. Raising an Exception from the Called C Program
    7. Nondefault Agents
    8. Maintaining External Procedures
      1. Dropping Libraries
      2. Data Dictionary
      3. Rules and Warnings
  12. A. Regular Expression Metacharacters and Function Parameters
    1. Metacharacters
    2. Functions and Parameters
      1. Regular Expression Functions
        1. REGEXP_COUNT (Oracle Database 11g and later)
        2. REGEXP_INSTR
        3. REGEXP_LIKE
        4. REGEXP_REPLACE
        5. REGEXP_SUBSTR
      2. Regular Expression Parameters
  13. B. Number Format Models
    1. Denoting Monetary Units
  14. C. Date Format Models
  15. Index
  16. About the Authors
  17. Colophon
  18. Copyright

Product information

  • Title: Oracle PL/SQL Programming, 6th Edition
  • Author(s): Steven Feuerstein, Bill Pribyl
  • Release date: February 2014
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449324452