Oracle Advanced PL/SQL Developer Professional Guide - Saurabh K. Gupta - E-Book

Oracle Advanced PL/SQL Developer Professional Guide E-Book

Saurabh K. Gupta

0,0
47,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural extension language for SQL and the Oracle relational database. Server-side PL/SQL is stored and compiled in the Oracle Database and runs within the Oracle executable. With this guide Oracle developers can work towards accomplishing Oracle 11g Advanced PL/SQL Professional certification, which is the second milestone for developers working at the Associate level. The Oracle Advanced PL/SQL Developer Professional Guide helps you master advanced PL/SQL concepts. Besides the clear and precise explanation on advanced topics, it also contains example code and demonstrations, which gives a sense of application and usage to readers.The book gives a deep insight that will help transform readers from mid-level programmers to professional database developers. It aims to cover the advanced features of PL/SQL for designing and optimizing PL/SQL code.This book starts with an overview of PL/SQL as the programming database language and outlines the benefits and characteristics of the language. The book then covers the advanced features that include PL/SQL code writing using collections, tuning recommendations using result caching, implementing VPD to enforce row level security, and much more. Apart from programming, the book also dives deep into the usage of the development tool SQL Developer, employing best practices in database environments and safeguarding the vulnerable areas in PL/SQL code to avoid code injection.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 476

Veröffentlichungsjahr: 2012

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Oracle Advanced PL/SQL Developer Professional Guide

Oracle Advanced PL/SQL Developer Professional Guide

Copyright © 2012 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2012

Production Reference: 1070512

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84968-722-5

www.packtpub.com

Cover Image by Tina Negus (<[email protected]>)

Credits

Author

Saurabh K. Gupta

Reviewers

Kamran Agayev A.

Mohan Dutt

Marcel Hoefs

Ronald Rood

Acquisition Editor

Rukshana Khambatta

Lead Technical Editor

Pramila Balan

Technical Editors

Vrinda Amberkar

Prasad Dalvi

Project Coordinator

Alka Nayak

Proofreaders

Linda Morris

Kevin McGowan

Indexer

Rekha Nair

Graphics

Valentina D'Silva

Manu Joseph

Production Coordinator

Nilesh R. Mohite

Cover Work

Nilesh R. Mohite

Foreword

Many of us learned to use PL/SQL recently; many did this many years ago. At that time simple problems required simple PL/SQL code, with lots of procedural code in it. Isn't the procedural part what PL/SQL is all about? Yes, it is, but this is also a threat because, when it is not used smartly, the procedural looping might become a performance hog.

Pl/SQL has evolved a lot. Bulk collections should be commonly in use now. Many programmers that support multiple vendors have little or no knowledge about Oracle collections. Because of this they write code like we did during v7, leaving the huge performance benefits, that Oracle has, untouched.

For these programmers this book is a very helpful addition to their library of knowledge. It helps them to easily perform the same task, but maybe 70 times faster, without making the code more complex. Using the advanced techniques described in the book you can do that. Don't mix up "advanced" with "complex". The fun about this is that many make their code complex using simple PL/SQL, trying to gain some performance, instead of effectively using advanced constructs in PL/SQL that in the end make the code easier to read and understand.

There is more to find in the book. Being a DBA, performance attracts a certain amount of attention. This is because performance is important. It greatly impacts the scalability of a database and the end user experience of the application. Other things you might find useful are the interfaces with the outside world, where external procedures can do work that does not fit the characteristics of a database.

Security is also something that attracts a DBA. Here you will find implementations of Virtual Private Database and enough remarks to keep the reader learning for quite a while. For example, how to protect against SQL injection? This again is a very interesting topic that should be taken very seriously. These days no network is safe. So scan every input.

I won't mention everything that is covered, just find a keyboard, your local database, and start reading. Try out the code samples and see where you can modify your existing code to take advantage of the new insights that the book will give you.

How advanced are the techniques described here depends on your mileage. For many the contents will be valuable enough to justify the term "advanced". As a reviewer it was a pleasure to read it and to try to push Saurabh Gupta to his limits. For me, I could use this book, even today.

Ronald Rood

Oracle ACE, Oracle DBA, OCM

PL/SQL is a programming language that is not only used by application developers, but also by database administrators in their daily tasks. This book contains information that every developer and even DBAs should know. As you read this book, you'll definitely learn a lot of new facts about PL/SQL programming. This book provides detailed information on general PL/SQL programming language, analyzing, tuning, tracing, and securing your code.

What I like most about the book is that it contains a lot of examples and helpful scripts for each chapter. This book also contains a lot of questions for the 1Z0-146 examination at the end of each chapter and it's one of the best guides for getting ready to pass the exam.

If you're a PL/SQL developer, whether a beginner or an expert, this book is for you.

Kamran Agayev A.

Oracle ACE, Oracle DBA Expert

About the Author

Saurabh K. Gupta got introduced to Oracle database around 5 years ago. Since then, he has been synchronizing his on job and off job interests with Oracle database programming. As an Oracle 11g Certified Advanced PL/SQL Professional, he soon moved from programming to database designing, development, and day-to-day database administration activities. He has been an active Oracle blogger and OTN forum member. He has authored and published more than 70 online articles and papers. His work can be seen in RMOUG journal, PSOUG, dbanotes, Exforsys, and Club Oracle. He shares his technical experience through his blog: http://sbhoracle.wordpress.com/. He is a member of All India Oracle Users Group (AIOUG) and loves to participate in technical meets and conferences.

Besides digging into Oracle, sketching and snooker are other pastimes for him. He can be reached through his blog SbhOracle for any comments, suggestions, or feedback regarding this book.

Acknowledgement

On a professional note, I am obliged to Ronald Rood, Kamran Agayev, Mohan Dutta, and Marcel Hoefs who reviewed the book with their own insights and perspectives. I was excited with the fact that the technical reviewers of my book are Oracle ACEs, highly respected, and recognized experts in the industry. I am grateful to Ronald who judged the worth of the book from the DBA perspective and helped me to extend my limits on the administrative aspect as well. Thanks to Kamran Agayev who consistently encouraged my writing styles and gave valuable inputs on the chapters. My obligations to Mohan Dutta and Marcel Hoefs who invested their valuable time in my work and added to the quality of the content. I would also like to express my gratitude for Arup Nanda, who has always been a great source of inspiration for me. His sessions and articles, covering all areas of Oracle database, have always been a great source of knowledge and motivation for me.

I would like to extend the appreciation to Packt Publishing for considering my proposal and accepting to go ahead on this book. My sincere thanks to Rukshana Khambatta, the Acquisition Editor at Packt for coordinating the kick-off activities of the book. I deeply appreciate the efforts of the Project Coordinator, Alka Nayak; the Lead Technical Editor, Pramila Balan; and the Technical Editors Vrinda Amberkar and Prasad Dalvi, whose diligent work and coordination added extra miles to the project. There was great tuning established between us and I am glad we worked parallely on the editorial process while abiding by the timelines.

It is correctly said that a man's personal and professional achievements are a showcase of his family's support and encouragement. I dedicate all my efforts and works to my parents, Suresh Chandra Gupta and Swadesh Gupta and family for their inevitable support, motivation, and sacrifices, and nurturing me towards all my achievements. Sincere thanks to my wife, Neha, and Sir J.B. Mall for their love, consistent support, and confidence in my endeavors and for being with me during my tough times.

About the Reviewers

Kamran Agayev A. is an Oracle ACE and Oracle Certified Professional DBA working at Azercell Telecom. He's an author of the book, Oracle Backup & Recovery: Expert secrets for using RMAN and Data Pump, and also shares his experience with a lot of step-by-step articles and video tutorials in his blog at http://kamranagayev.com. He also presents at Oracle OpenWorld, TROUG, and local events.

Mohan Dutt is an Oracle expert, having presented more than 55 sessions at Oracle conferences worldwide. An Oracle evangelist at large, he was awarded Member of the Year by Oracle Applications User Group (OAUG) in 2007. He authors the world's first blog dedicated entirely to Oracle certification. He has founded and chaired 3 Oracle Special Interest Groups (SIG). He was recognized as an Oracle ACE in 2011.

Marcel Hoefs learned his trade participating in numerous Oracle development projects, as an Oracle developer, since 1997. Being a specialist in SQL and PL/SQL database development, Oracle Forms, Reports, and Designer, Marcel currently works as a Technical Architect, Lead Developer, and Performance Specialist. With the advent of web technologies such as Web Services, ADF, and APEX, he currently specializes in innovative solutions opening up traditional Oracle database systems to the Web. As a senior Oracle Consultant with CIBER, he is also an Oracle competence leader, organizing and participating in knowledge sharing sessions with participants from within and outside CIBER.

Ronald Rood is an innovating Oracle DBA with over 20 years of IT experience. He has built and managed cluster databases on almost each and every platform that Oracle has ever supported, from the famous OPS databases in version 7, until the latest RAC releases, currently being 11g. Ronald is constantly looking for ways to get the most value out of the database to make the investment for his customers even more valuable. He knows how to handle the power of the rich Unix environment very well and this is what makes him a first class trouble-shooter and a true Oracle ACE. Next to the spoken languages such as Dutch, English, German, and French, he also writes fluently in many scripting languages.

Currently, Ronald is a principal consultant working for CIBER in The Netherlands where he cooperates in many complex projects for large companies where downtime is not an option. CIBER or CBR is a global full service IT provider and Oracle Platinum Partner.

Ronald often replies in the Oracle forums, writes his own blog (http://ronr.blogspot.com) called "From errors we learn" and writes for various Oracle related magazines. He also wrote a book, Mastering Oracle Scheduler in Oracle 11g Databases, where he fills the gap between the Oracle documentation and customers' questions. You can find him on Twitter at http://twitter.com/ik_zelf.

Ronald has lots of certifications:

Oracle Certified MasterOracle Certified ProfessionalOracle Database 11g Tuning SpecialistOracle Database 11g Data Warehouse Certified Implementation Specialist

Ronald fills his time with Oracle, his family, sky-diving, radio controlled model airplane flying, running a scouting group, and having a lot of fun.

He quotes, "A problem is merely a challenge that might take a little time to be solved".

www.PacktPub.com

Support files, eBooks, discount offers, and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Instant Updates on New Packt Books

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.

Preface

Oracle Database 11g brings in a weighted package of new features which takes the database management philosophy from instrumental to self-intelligence level. The new database features, which are more properly called "advanced", rather than "complex", aim either of the two purposes:

Replacement of a workaround solution with a permanent one (as an enhancement)By virtue of routine researches and explorations, introduce a fresh feature to help database administrators and developers with their daily activities

Oracle Advanced PL/SQL Professional Guide focuses on advanced features of Oracle 11g PL/SQL. The areas targeted are PL/SQL code design, measuring and optimizing PL/SQL code performance, and analyzing PL/SQL code for reporting purposes and immunizing against attacks. The advanced programming topics such as usage of collections, implementation of VPD, interaction with external procedures in PL/SQL, performance orientation by caching results, tracing and profiling techniques, and protecting against SQL injection will familiarize you with the latest programming findings, trends and recommendations of Oracle. In addition, this book will help you to learn the latest, best practices of PL/SQL programming in terms of code writing, code analyzing for reporting purposes, tracing for performance, and safeguarding the PL/SQL code against hackers.

 

An investment in knowledge pays the best interest.

  --Benjamin Franklin

The fact remains that the technical certifications from Oracle Corporation establish a benchmark of technical expertise and credibility, and set the tone of an improved career path for application developers. With the growing market in database development, Oracle introduced Advanced PL/SQL Professional Certification (1Z0-146) in the year 2008. The OCP (1Z0-146) certification exam tests aspirants on knowledge of advanced PL/SQL concepts (validated up to Oracle 11g Release 1). An advanced PL/SQL professional is expected to independently design, develop, and tune the PL/SQL code which can efficiently interface database systems and user applications.

The book, Oracle Advanced PL/SQL Professional Guide, is a sure recommendation for the preparation of the OCP certification (1Z0-146) exam. Advanced PL/SQL topics are explained thoroughly with the help of demonstrations, figures, and code examples. The book will not only explain a feature, but will also teach its implementation and application. You can easily pick up the content structure followed in the book. The code examples can be tried on your local database setups to give you a feel of the usage of a specific feature in real time scenarios.

What this book covers

Chapter 1, Overview of PL/SQL Programming Concepts, covers the overview of PL/SQL as the primary database programming language. It describes the characteristics of the language and its strengths in database development. This chapter speeds up with the structure of a PL/SQL block and reviews PL/SQL objects such as procedures, functions, and packages. In this chapter, we will also learn to work with SQL Developer.

Chapter 2, Designing PL/SQL Code, discusses the handling of cursors in a PL/SQL program. This chapter helps you to learn the guidelines for designing a cursor, usage of cursor variables, and cursor life cycle.

Chapter 3, Using Collections, introduces a very important feature of PL/SQL—collections. A collection in a database is very similar to arrays or maps in other programming languages. This chapter compares collection types and makes recommendations for the appropriate selection in a given situation. This chapter also covers the collection methods which are utility APIs for working with collections.

Chapter 4, Using Advanced Interface Methods, teaches how to interact with an external program written in a non-PL/SQL language, within PL/SQL. It demonstrates the execution steps for external procedures in PL/SQL. This steps describe the network configuration on a database server (mounted on Windows OS), library object creation, and publishing of a non-language program as an external routine.

Chapter 5, Implementing VPD with Fine Grained Access Control, introduces the concept of Fine Grained Access in PL/SQL. The working of FGAC as Virtual Private Database is explained in detail along with an insight into its key features. You will find stepwise implementation of VPD with the help of policy function and the DBMS_RLS package. This chapter also describes policy enforcement through application contexts.

Chapter 6, Working with Large Objects, discusses the traditional and conventional way of handling large objects in an Oracle database. This chapter starts with the familiarization of the available LOB data types (BLOB, CLOB, BFILE, and Temporary LOBs) and their significance. You will learn about the creation of LOB types in PL/SQL and their respective handling operations. This chapter demonstrates the management of LOB data types using SQL and the DBMS_LOB package.

Chapter 7, Using SecureFile LOBs, introduces one of the key innovations in Oracle 11g —SecureFiles. SecureFiles are upgraded LOBs which work on an improved philosophy of storage and maintenance. The key improvements of SecureFiles—deduplication, compression, and encryption—are licensed features. This chapter discusses and demonstrates the implementation of these three properties. You will learn how to migrate (or rather upgrade) the existing older LOBs into a new scheme—SecureFiles. The migration techniques covered use an online redefinition method and a partition method.

Chapter 8, Compiling and Tuning to Improve Performance, describes fair practices in effective PL/SQL programming. You will be very interested to discover how better code writing impacts code performance. This chapter explains an important aspect of query optimization—the PLSQL_OPTIMIZE_LEVEL parameter. The code behavior and optimization strategy at each level will help you to understand the language internals. Subsequently, the new PRAGMA feature will give you a deeper insight into subprogram inlining concepts.

Chapter 9, Caching to Improve Performance, covers another hot feature of Oracle 11g Database—server-side result caching. The newly introduced server-side cache component in SGA holds the results retrieved from SQL query or PL/SQL function. This chapter describes the configuration of a database server for caching feature through related parameters, implementation in SQL through RESULT_CACHE hint and implementation in PL/SQL function through the RESULT_CACHE clause. Besides the implementation section, this chapter teaches the validation and invalidation of result cache, using the DBMS_RESULT_CACHE package.

Chapter 10, Analyzing PL/SQL Code, helps you to understand and learn code diagnostics tricks and code analysis for reporting purposes. You will learn to monitor identifier usage, about compilation settings, and generate the subsequent reports from SQL Developer. This chapter discusses a very important addition in Oracle 11g—PL/Scope. It covers the explanations and illustrations to generate the structural reports through the dictionary views. In addition, this chapter also demonstrates the use of the DBMS_METADATA package to retrieve and extract metadata of database objects from the database in multiple formats.

Chapter 11, Profiling and Tracing PL/SQL Code, aims to demonstrate the tracing and profiling features in PL/SQL. The tracing demonstration uses the DBMS_TRACE package to trace the enabled or all calls in a PL/SQ program. The PL/SQL hierarchical profiler is a new innovation in 11g to identify and report the time consumed at each line of the program. The biggest benefit is that raw profiler data can be reproduced meaningfully into HTML reports.

Chapter 12, Safeguarding PL/SQL Code against SQL Injection Attacks, discusses the SQL injection as a concept and its remedies. The SQL injection is a serious attack on the vulnerable areas of the PL/SQL code which can lead to extraction of confidential information and many fatal results. You will learn the impacts and precautionary recommendations to avoid injective attacks. This chapter discusses the preventive measures such as using invoker's rights, client input validation tips, and using DBMS_ASSERT to sanitize inputs. It concludes on the testing strategies which can be practiced to identify vulnerable areas in SQL.

Appendix, Answers to Practice Questions, contains the answers to the practice questions for all chapters.

What you need for this book

You need to have a sound understanding of SQL and PL/SQL basics. You must have mid-level experience of working with Oracle programming.

Who this book is for

The book is for associate-level developers who are aiming for professional-level certification. This book can also be used to understand and practice advanced PL/SQL features of Oracle.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "The SERVEROUTPUT parameter is a SQL*Plus variable which enables the printing of block debug messages."

A block of code is set as follows:

/*Start the PL/SQL block*/ DECLARE /*Declare a local variable and initialize with a default value*/ L_NUM NUMBER := 15; L_RES NUMBER; BEGIN /*Calculate the double of local variable*/ L_RES := L_NUM *2; /*Print the result*/ DBMS_OUTPUT.PUT_LINE('Double of '||TO_CHAR(L_NUM)||' is '||TO_ CHAR(L_RES)); END; / Double of 15 is 30 PL/SQL procedure successfully completed.

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

/*Check if the cursor is already open*/ IF NOT C_EMP%ISOPEN THEN DBMS_OUTPUT.PUT_LINE('Cursor is closed....Cursor has to be opened'); END IF;

Any command-line input or output is written as follows:

SQL> HELP INDEX

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Right-click on the Connections node and select New Connection... to open the connection wizard"

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that title.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Overview of PL/SQL Programming Concepts

In the summer of 1970, Dr. E.F. Codd published his paper, A Relational Model of Data for Large Shared Data Banks, for the ACM journal. The projected model was accepted and subsequently an interactive database language, SQL, was developed by IBM Corporation, Inc. In 1979, Relational Software, Inc. stepped into the commercial implementation of SQL as the primary RDBMS language. Later, Relational Software, Inc. transformed into Oracle and since then, its story has been a success.

The Structured Query Language or SQL (pronounced "Sequel") has been used as the primary interactive language for all data operations such as selection, creation, and manipulation. Besides data operations, the language has administrative and monitoring features which ensure data consistency, integrity, and object controllability. By virtue of its multifaceted and versatile behavior in data centric environments, all major RDBMS support SQL as a database interaction language. The universal acceptance of SQL eases the logical usability across the databases (such as MySQL and SQL Server) with minor syntactical modifications.

Over the initial years of exploration, the procedural limitations of SQL were identified which prevented it from being an efficient programming language amongst the fourth generation languages. The head to head competition and demanding expectations of the industry led to the evolution of a procedural version of SQL in the Oracle database family. The first version of PL/SQL was debuted in Oracle 6.0 (in 1991) as an optional procedural extension in SQL* forms. Since its induction, PL/SQL has emerged as a strong and proven database programming language. With the release of Oracle 11g database (in 2007), PL/SQL has successfully stepped into its 11.0 version.

In this chapter, we will tour the Oracle PL/SQL programming concepts to get an overview of PL/SQL block, subprograms, exception handling, and object dependencies. The chapter outlines the benefits and characteristics of the language in the following sections:

Introduction to PL/SQLOracle development tools—SQL Developer and SQL*PlusRecapitulate procedures, functions, packages, and cursorsException handlingObject dependenciesMajor Oracle supplied packages

PL/SQL—the procedural aspect

PL/SQL stands for Procedural Language-Structured Query Language. It is a significant member of the Oracle programming toolset and extensively used to code server-side programs. Some of its major accomplishments are that it:

Supports programming constructs to design a program unitImplements business logic in an Oracle server using cursors and database objects such as packages, subprograms, and many moreMakes the application portability easierPreserves execution privileges and transaction managementMakes use of advanced PL/SQL features such as collections to process bulk data and enhance performanceAllows external programs to be executed from PL/SQL

As a language, the different perceptions of PL/SQL are as follows:

Aninteractiveandstructuredlanguage: The PL/SQL language comprises of a glossary of expressive and explanatory keywords. The self-indenting, structured feature, and ANSI compatibility ensures quick learning and adaptation for an individual.Anembeddedlanguage: A PL/SQL program is not environment-dependent but can be easily invoked from any recognized Oracle development environment such as SQL* Plus, SQL Developer, TOAD, reporting tools, and so on.Anintegrallanguage: A database manager can easily integrate a PL/SQL server-side program with other client-side programming interfaces such as Java, C++, or .NET. The PL/SQL procedures or subprograms can be invoked from client programs as executable statements.

My first PL/SQL program

A PL/SQL block is the elementary unit of a program which groups a set of executable procedural statements. A block has defined "start" and "end" stages and it has three forms:

Anonymous: This block is an unnamed PL/SQL block which is persistent for single execution onlyNamed: This block contains named PL/SQL programs which are stored physically in the database as schema objectsNested: A block within another PL/SQL block forms a nested block structure

The skeleton of a PL/SQL block has four sections:

Header: This is an optional section which is required for the named blocks. It contains block name, block owner's name, parameter specifications, and return type specification (for functions).Declaration: This is an optional section which is used for declaration of local variables, cursors, and local subprograms. The DECLARE keyword indicates the beginning of the declaration section.Execution: This is the mandatory section of a PL/SQL block which contains the executable statements. These statements are parsed by the PL/SQL engine and executed on the block invocation. The BEGIN and END keywords indicate the beginning and end of an executable section.Exception: This is the optional section of the block which contains the exception handlers. The appropriate exception handler is activated upon any exception raised from the executable section to suggest alternate steps. The EXCEPTION keyword indicates the start of the exception section.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The following block diagram shows the structure of a PL/SQL block. The sections marked in red are the mandatory ones with the others being optional:

The PL/SQL following program illustrates the declaration and executable sections. The program declares a number variable, calculates its double value, and prints the result.

/*Enable the Serveroutput to display block messages*/ SET SERVEROUTPUT ON

Note

The SERVEROUTPUT parameter is a SQL*Plus variable which enables the printing of block debug messages. It is discussed in detail in the SQL*Plus section.

/*Start the PL/SQL block*/ DECLARE /*Declare a local variable and initialize with a default value*/ L_NUM NUMBER := 15; L_RES NUMBER; BEGIN /*Calculate the double of local variable*/L_RES := L_NUM *2;/*Print the result*/ DBMS_OUTPUT.PUT_LINE('Double of '||TO_CHAR(L_NUM)||' is '||TO_CHAR(L_RES)); END; / Double of 15 is 30 PL/SQL procedure successfully completed.

PL/SQL development environments

Oracle provides and recommends the usage of its development tools for SQL writing and code execution. This chapter will cover the two main developer tools from Oracle:

SQL DeveloperSQL*Plus

However, there are many SQL development interfaces available on the Web such as TOAD from Quest Software, Dreamcoder by Mentat Technologies, and so on.

SQL Developer

SQL Developer is a Graphical User Interface (GUI) tool from the Oracle Corporation. It is free to use and includes a wide spectrum of new features with each of its releases. It allows the users to perform database activities such as SQL writing, PL/SQL execution, DBA activities easily, interactively, and considerably within time. Many of the database utilities such as unit testing, profiling, extended search, and SQL monitoring have been implemented as GUI utilities and can be easily used with the PL/SQL programs. The latest version of SQL Developer is 3.1 (3.1.07.42) which has been released on February 7, 2012. SQL Developer can be downloaded from the Oracle Technology Network link:

http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html

The latest release of the database development tool offers new features such as inclusion of RMAN under DBA navigator, support for data pump technology, renovated data copy and difference features, support for migration to Teradata and Sybase, and generation of PDF reports.

The key accomplishments offered by SQL Developer are:

Authenticating and connecting to multiple Oracle databasesAllowing creation and maintenance of schema objects packages, procedures, functions, triggers, indexes and viewsQuerying and manipulating the dataDatabase utilities such as version maintenance, admin activities, migration, and database exportSupport for SQL*Plus commands

The major offerings shown in the preceding list are by virtue of the tool features. The salient features of the SQL Developer tool are:

Connection browser and Schema browserSQL Worksheet and Query BuilderDatabase import and export utility wizardDatabase user-defined reportsCode repository configuration for version controlDatabase copy and migration utility wizardThird-party databasesOracle APEX integrationTimesTen integration

The following screenshot shows the Start Page of Oracle SQL Developer:

SQL Developer—the history

The following flowchart demonstrates the release history of SQL Developer:

Creating a connection

Once the SQL Developer tool is downloaded from the Oracle Technology Network (OTN) website (in ZIP format), it is ready for use and does not require any installation. The target server can be Oracle 11g database software. For educational and practice purposes, Oracle recommends the usage of the Oracle Database Express edition. It can be downloaded for free from the following URL:

http://www.oracle.com/technetwork/database/express-edition/overview/index.html

By default, the database software installation takes care of the Oracle database configuration and Oracle network configuration.

Now, we shall start working with SQL Developer to connect to the database. The first and foremost step is establishing the connection to the target database.

The steps for creating a connection in SQL Developer are as follows:

Double-click on \\sqldeveloper\sqldeveloper.exe.Go to Menu | View | Connections. A tabbed page titled Connections will appear at the left-hand side of the page. The top node of the tree is Connections.Right-click on the Connections node and select New Connection… to open the connection wizard.Specify the connection name, username, password, connection type, role (DBA or default), host name, port number, and SID of the target database. Connection type must be Basic if you specify the connection parameters. If TNS, then select a connection string from the Network Alias drop-down list (which is in sync with the TNSNAMES.ORA file)Check the Save Password option to allow the Connection wizard to remember the password of this user.Click on the Test button to verify the connection. The status (success or error message) will appear in the wizard's console.Click on the Connect button to connect to the database. By default, it opens a SQL Worksheet to write and execute queries.

SQL Worksheet

The SQL Worksheet window is the primary editor to perform database activities. It is used to write and execute SQL statements, PL/SQL code, and SQL*Plus commands.

A new worksheet can be opened in two ways:

Hitting the shortcut key, Alt + F10Navigating to Tools | SQL Worksheet

When a SQL worksheet is opened by following either of the preceding options, a window pops up which prompts the user to select the database connection applicable for the current worksheet. The available database connection to open a new SQL worksheet can be selected from the drop-down option:

The worksheet contains multiple, quick utility actions as iconized menus. These menus perform a few of the basic activities associated with a script execution; for example, running a script, autotrace, and explain plan. With reference to the preceding screenshot of a sample SQL worksheet, the menu functions are described as follows:

Run Statement: It executes the statement at the current cursor position.Run Script: It executes a script.Autotrace: It generates trace information about the statement.Explain Plan: It generates an execution plan for the query, starting at the current cursor positionSQL Tuning Advisor: It advises the tuning tips for the current user. The user must have ADVISOR system privilege to use this icon.Commit: It commits the ongoing transaction in the current session.Rollback: It rollbacks the ongoing transaction in the current session.Unshared SQL Worksheet: It opens a new SQL worksheet.To Upper/Lower/InitCaps: It changes the string case of the statement to upper or lower or initial caps.Clear: It clears all the statements from the current SQL Worksheet.SQL History: It opens a dialog box with all the SQL statements executed for this user.

Executing a SQL statement

A SQL statement can be executed from the SQL Worksheet in three ways:

Selecting the SQL statement and clicking on the Run Statement or Run Script icon from the Worksheet menuSelecting the SQL statement and pressing F9Terminating the SQL statement with a semicolon and pressing Ctrl + Enter

The result of the SQL statement execution is displayed in the Query Result tab. The following screenshot shows the execution of the SELECT statement using Ctrl + Enter:

Note

The SQL Worksheet doesn't supports some SQL*Plus commands such as append, archive, attribute, and break.

Calling a SQL script from SQL Developer

A SQL script saved on a specific OS location can be invoked from SQL Developer Worksheet. We will cover an overview of the two methods to execute a saved SQL script:

A saved SQL script from an OS location can be invoked in The SQL Worksheet. It can be executed either by clicking on the Run Script (or F5) icon, or Ctrl + Enter or F9. The output of the script is displayed in the Script Output tab.Another option to invoke a saved script is to open it from the menu path, File | Open. Navigate to the script location and open the script. The script code would be opened in a new SQL Worksheet. Note that the worksheet's name is renamed as the actual script name. Now, the code can be executed using the Run Script icon.

A SQL script, Test_Script.sql at the C:\Labs\ location contains the following SQL statement:

SELECT * FROM EMPLOYEES /

As shown in the following screenshot, the script has been invoked in the SQL Worksheet using SQL*Plus execute command, @:

Creating and executing an anonymous PL/SQL block

An anonymous PL/SQL block can be written and executed, as shown in the following screenshot. Note that the PL/SQL block must be terminated with a semicolon. The Script Output tab displays the confirmed status of the block execution as anonymous block completed.

The block output can be viewed in the Dbms Output Tab. This tab remains hidden until it can be enabled and activated by navigating to Menu | View | Dbms Output:

Debugging the PL/SQL code

The PL/SQL code can be debugged to observe the execution flow. The PL/SQL blocks and stored subprograms (procedures, functions, triggers, and packages) can be compiled for debugging.

An anonymous PL/SQL block can be debugged by selecting the block and choosing the Debug option from the right-click option list, as shown in the following screenshot:

Once the Debug option is clicked, the debugging starts and the following output appears in the Messages tab:

Connecting to the database ORADEV. Executing PL/SQL: ALTER SESSION SET PLSQL_DEBUG=TRUE Executing PL/SQL: CALL DBMS_DEBUG_JDWP.CONNECT_TCP( '127.0.0.1', '3953' ) Debugger accepted connection from database on port 3953. Executing PL/SQL: CALL DBMS_DEBUG_JDWP.DISCONNECT() Sum of two given Numbers:35 Process exited. Disconnecting from the database ORADEV. Debugger disconnected from database.

Note

The database user must have DEBUGCREATESESSION and DEBUGANYPROCEDURE privileges to debug the PL/SQL code.

Likewise, the stored subprograms can be compiled using Compile for Debug to mark them for the debugging process. Henceforth, the execution of the subprograms can be traced line by line using the Oracle supplied package, DBMS_TRACE.

Editing and saving the scripts

SQL Developer provides enhanced editing features while writing the code in the SQL Worksheet. The automated code completion suggestion in the drop-down menu effectively eases the code writing. Besides, the PL/SQL syntax highlights, member method drop-down menu, code folding, and bookmarks are the other code editing features available in the SQL Worksheet.

A stored subprogram in the schema object tree can be opened in the SQL Worksheet for editing.

The following screenshot shows the auto-code completion feature of SQL Developer. You can select any of the available options as suited for the script:

The SQL statements or PL/SQL code in the current SQL Worksheet can be saved as a text or SQL file at any specified location on the OS. Either follow the full navigation path (File | Save) or use the quick utility Save icon. Once the Windows Save dialog box appears, navigate to the target location, specify the filename, and click on the Save button.

SQL*Plus

SQL*Plus is a command-line utility interface and has been one of the primitive interfaces used by database professionals for database activities. The SQL*Plus session is similar to the SQL Worksheet of SQL Developer, where you can write and execute SQL statements and PL/SQL code.

Starting from Oracle 5.0, the SQL*Plus interface has been a part of the Oracle development kit. With regular revisions and enhancements in subsequent Oracle releases, it has been deprecated in the Oracle 11g release to recommend the use of SQL Developer. However, the SQL*Plus environment can still be established from command prompt.

The evolution cycle of SQL*Plus is shown in the following diagram:

The Oracle SQL*Plus session can be invoked from sqlplus.exe. This executable file is located in the $Oracle_home\bin folder. Alternatively, it can also be invoked by performing the following steps:

Open command prompt.Enter SQLPLUS, press Enter. Note the SQL*Plus welcome message. The editor will prompt for a username and password.Enter the username, password, and database connection string. Press Enter.Connect to the database:
C:\>SQLPLUS SQL*Plus: Release 11.2.0.1.0 Production on Fri Dec 23 14:20:36 2011 Copyright (c) 1982, 2010, Oracle. All rights reserved. Enter user-name: ORADEV/ORADEV Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production With the Partitioning, OLAP, Data Mining and Real Application Testing options SQL>

SQL*Plus has its own set of shell commands which can be used for the execution of scripts, editing the code, and formatting the query output.

The complete set of SQL*Plus commands can be obtained by entering HELP [INDEX |?] after the SQL prompt. The complete list of SQL*Plus commands are as follows:

SQL> HELP INDEX Enter Help [topic] for help. @ COPY PAUSE SHUTDOWN @@ DEFINE PRINT SPOOL / DEL PROMPT SQLPLUS ACCEPT DESCRIBE QUIT START APPEND DISCONNECT RECOVER STARTUP ARCHIVE LOG EDIT REMARK STORE ATTRIBUTE EXECUTE REPFOOTER TIMING BREAK EXIT REPHEADER TTITLE BTITLE GET RESERVED WORDS (SQL) UNDEFINE CHANGE HELP RESERVED WORDS (PL/SQL) VARIABLE CLEAR HOST RUN WHENEVER OSERROR COLUMN INPUT SAVE WHENEVER SQLERROR COMPUTE LIST SET XQUERY CONNECT PASSWORD SHOW

Executing a SQL statement in SQL*Plus

A SQL statement can be executed in the SQL*Plus editor, terminated by a semicolon or a forward slash (/). The following screenshot demonstrates the execution of a SELECT statement. The query selects the names of all employees from the EMPLOYEES table:

Executing an anonymous PL/SQL block

Similar to the execution in SQL Developer, a PL/SQL block can be executed in SQL*Plus. The SERVEROUTPUT environment variable has to be set to ON to display the results in the editor.

The following screenshot demonstrates the execution of a PL/SQL block in SQL*Plus:

Procedures

A procedure is a derivative of PL/SQL block structure which is identified by its own specific name. It is stored as a schema object in the database and implements business logic in the applications. For this reason, procedures are often referred to as Business Managers of PL/SQL which not only maintain the business logic repository, but also demonstrate solution scalability and a modular way of programming.

The characteristics of procedures are as follows:

A procedure can neither be called from a SELECT statement nor can it appear as a right-hand operand in an assignment statement. It has to be invoked from the executable section of a PL/SQL block as a procedural statement.They can optionally accept parameters in IN, OUT, or INOUT mode.This implies that the only possibility for a procedure to return a value is through OUT parameters, but not through the RETURN[value] statement. The RETURN statement in a procedure is used to exit the procedure and skip the further execution.

For recapitulation, the following table differentiates between the IN, OUT, and INOUT parameters:

IN

OUT

IN OUT

Default parameter mode

Has to be explicitly defined

Has to be explicitly defined

Parameter's value is passed into the program from the calling environment

Parameter returns a value back to the calling environment

Parameter may pass a value from the calling environment to the program or return a value to the calling environment

Parameters are passed by reference

Parameters are passed by value

Parameters are passed by value

May be constant, literal, or initialized variable

Uninitialized variable

Initialized variable

Can hold the default value

Default value cannot be assigned

Default value cannot be assigned

The syntax for a procedure is as follows:

CREATE [OR REPLACE] PROCEDURE [Procedure Name] [Parameter List] [AUTHID DEFINER | CURRENT_USER] IS [Declaration Statements] BEGIN [Executable Statements] EXCEPTION [Exception handlers] END [Procedure Name];

The following standalone procedure converts the case of the input string from lowercase to uppercase:

/*Create a procedure to convert the string from lower case to upper case*/ CREATE OR REPLACE PROCEDURE P_TO_UPPER (P_STR VARCHAR2) IS /*Declare the local variables*/ L_STR VARCHAR2(50); BEGIN /*Convert the case using UPPER function*/ L_STR := UPPER(P_STR); /*Display the output with appropriate message*/ DBMS_OUTPUT.PUT_LINE('Input string in Upper case : '||L_STR); END; / Procedure created.

Executing a procedure

A procedure can be either executed from SQL*Plus or from a PL/SQL block. The P_TO_UPPER procedure can be executed from SQL*Plus.

The following illustration shows the execution of the procedure from SQL*Plus (note that the parameter is passed using the bind variable):

/*Enable the SERVEROUTPUT parameter to print the results in the environment*/ SQL> SET SERVEROUTPUT ON /*Declare a session variable for the input*/ SQL> VARIABLE M_STR VARCHAR2(50); /*Assign a test value to the session variable*/ SQL> EXECUTE :M_STR := 'My first PLSQL procedure'; PL/SQL procedure successfully completed. /*Call the procedure P_TO_UPPER*/ SQL> EXECUTE P_TO_UPPER(:M_STR); Input string in Upper case : MY FIRST PLSQL PROCEDURE PL/SQL procedure successfully completed.

The P_TO_UPPER procedure can be called as a procedural statement within an anonymous PL/SQL block:

/*Enable the SERVEROUTPUT parameter to print the results in the environment*/ SQL> SET SERVEROUTPUT ON /*Start a PL/SQL block*/ SQL> BEGIN /*Call the P_TO_UPPER procedure*/ P_TO_UPPER ('My first PLSQL procedure'); END; / Input string in Upper case : MY FIRST PLSQL PROCEDURE PL/SQL procedure successfully completed.

Functions

Like a procedure, a function is also a derivative of a PL/SQL block structure which is physically stored within a database. Unlike procedures, they are the "workforce" in PL/SQL and meant for calculative and computational activities in the applications.

The characteristics of functions are as follows:

Functions can be called from SQL statements (SELECT and DMLs). Such functions must accept only IN parameters of valid SQL types. Alternatively, a function can also be invoked from SELECT statements if the function body obeys the database purity rules.Functions can accept parameters in all three modes (IN, OUT, and INOUT) and mandatorily return a value. The type of the return value must be a valid SQL data type (not be of BOOLEAN, RECORD, TABLE, or any other PL/SQL data type).

The syntax for a function is as follows:

CREATE [OR REPLACE] FUNCTION [Function Name] [Parameter List] RETURN [Data type] [AUTHID DEFINER | CURRENT_USER] [DETERMINISTIC | PARALLEL_ENABLED | PIPELINES] [RESULT_CACHE [RELIES_ON (table name)]] IS [Declaration Statements] BEGIN [Executable Statements] RETURN [Value] EXCEPTION [Exception handlers] END [Function Name];

The standalone function, F_GET_DOUBLE, accepts a single argument and returns its double:

/*Create the function F_GET_DOUBLE*/ CREATE OR REPLACE FUNCTION F_GET_DOUBLE (P_NUM NUMBER) RETURN NUMBER /*Specify the return data type*/ IS /*Declare the local variable*/ L_NUM NUMBER; BEGIN /*Calculate the double of the given number*/ L_NUM := P_NUM * 2; /*Return the calculated value*/ RETURN L_NUM; END; / Function created.

Function—execution methods

As a common feature shared among the stored subprograms, functions can be invoked from a SQL*Plus environment and called from a PL/SQL as a procedural statement.

The following code snippet demonstrates the execution of a function from a SQL*Plus environment and its return value have been captured in a session bind variable:

/*Enable the SERVEROUTPUT parameter to print the results in the environment*/ SQL> SET SERVEROUTPUT ON /*Declare a session variable M_NUM to hold the function output*/ SQL> VARIABLE M_NUM NUMBER; /*Function is executed and output is assigned to the session variable*/ SQL> EXEC :M_NUM := F_GET_DOUBLE(10); PL/SQL procedure successfully completed. /*Print the session variable M_NUM*/ SQL> PRINT M_NUM M_NUM ---------- 20

Now, we will see the function execution from an anonymous PL/SQL block as a procedural statement:

/*Enable the SERVEROUTPUT parameter to print the results in the environment*/ SQL> SET SERVEROUTPUT ON SQL>DECLARE M_NUM NUMBER; BEGIN M_NUM := F_GET_DOUBLE(10); DBMS_OUTPUT.PUT_LINE('Doubled the input value as : '||M_NUM); END; / Doubled the input value as : 20 PL/SQL procedure successfully completed.

Restrictions on calling functions from SQL expressions

Unlike procedures, a stored function can be called from SELECT statements; provided it must not violate the database purity levels. These rules are as follows:

A function called from a SELECT statement cannot contain DML statementsA function called from a UPDATE or DELETE statement on a table cannot query (SELECT) or perform transaction (DMLs) on the same tableA function called from SQL expressions cannot contain the TCL (COMMIT or