Ocp - Sql&pl_sql(vol3)

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Ocp - Sql&pl_sql(vol3) as PDF for free.

More details

  • Words: 23,345
  • Pages: 304
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder Volume Three S Participant Guide

Edition 1.1 M03991 T1001E11

Authors

Copyright EĂOracle Corporation, 1992, 1996. All rights reserved.

Neena Kochhar Debby Kramer

This documentation contains proprietary information of Oracle Corporation; it is provided under a license agreement containing restrictions on use and discloĆ sure and is also protected by copyright law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the folĆ lowing legend is applicable:

Technical Contributors and Reviewers

Restricted Rights Legend

Christian Bauwens Debra Bowman Lenny Brunson Jackie Collins Ralf Durben Brian Fry Anthony Holbrook Karlene Jensen Sarah Jones Glenn Maslen Sundar Nagarathnam Sandra Schrick Ulrike Schwinn Rosemarie Truman Jenny Tsai Laura Van Deusen

Use, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to be Restricted Rights softĆ ware under Federal law, and as set forth in subparagraph (c) (1) (ii) of DFARS 252.227Ć7013, Rights in Technical Data and Computer Software (October 1988). This material or any portion of it may not be copied in any form or by any means without the express prior written permission of the Worldwide Education Services group of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties. If this documentation is delivered to a U.S. Government Agency not within the DeĆ partment of Defense, then it is delivered with Restricted Rights," as defined in FAR 52.227Ć14, Rights in DataĆGeneral, including Alternate III (June 1987). The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Worldwide Education Services, Oracle Corporation, 500 Oracle Parkway, Box 659806, RedĆ wood Shores, CA 94065. Oracle Corporation does not warrant that this document is error free. SQL*Plus, PL/SQL, Procedure Builder, Developer/2000, Oracle7 Server, Oracle Server, Discoverer/2000, and Designer/2000 are trademarks or registered tradeĆ marks of Oracle Corporation. All other products or company names are used for identification purposes only, and may be trademarks of their respective owners.

Publishers Stephanie Jones Kimberly Lee Jennifer Robertson Mark Turangan

18 Overview of PL/SQL

18Ć2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives This lesson provides an overview of how to create and use PL/SQL program units and subprograms using Oracle Procedure Builder. At the end of this lesson, you should be able to D

Determine the benefits of accessing the Oracle7 database with PL/SQL.

D

Describe basic PL/SQL program constructs.

D

Describe the Oracle Procedure Builder tool.

Overview of PL/SQL

18Ć3

18Ć4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview What Is PL/SQL? PL/SQL (Procedural Language/SQL) is an extension to SQL, incorporating many of the design features of programming languages of recent years. It allows the data manipulation and query statements of SQL to be included within block-structured and procedural units of code, making PL/SQL a powerful transaction processing language. Benefits from PL/SQL You can take advantage of the procedural capabilities of PL/SQL, which are unavailable in SQL. Modularize Program Development D Group logically related statements within blocks. D

Nest sub-blocks inside larger blocks to build powerful programs.

D

Break down a complex problem into a set of manageable, well-defined, logical modules, and implement them with blocks.

Declare Identifiers D Declare variables, constants, cursors, and exceptions, and then use them in SQL and procedural statements. D

Declare variables belonging to simple and composite datatypes.

D

Declare variables dynamically based upon the data structure of tables and columns in the database.

Program with Procedural Language Control Structures D Execute a sequence of statements conditionally. D

Execute a sequence of statements iteratively in a loop.

D

Process individually the rows returned by a multiple-row query with an explicit cursor.

D

Combine PL/SQL with Oracle tools, such as Developer/2000 Forms, to group associated commands together to control execution.

Handle Errors D Process Oracle7 Server errors with exception handling routines. Declare user-defined error conditions and process them with exception handling routines. Continued

D

Overview of PL/SQL

18Ć5

18Ć6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview

continued

Benefits of PL/SQLĊcontinued Portability D Since PL/SQL is native to Oracle, you can move programs to any host environment that supports Oracle and PL/SQL. D

You can also move code between the Oracle7 Server and your application environment using Procedure Builder’s drag-and-drop capabilities.

Integration D PL/SQL plays a central role to both the Oracle7 Server (through stored procedures, database triggers, and packages) and Oracle development tools (through Developer/2000 component triggers). D

Variables and datatypes in PL/SQL and SQL are compatible. Therefore, PL/SQL bridges the gap between convenient access to database technology and the need for procedural programming capabilities.

Improve Performance D PL/SQL can improve the performance of an application. The benefits differ depending upon the execution environment. D

PL/SQL groups SQL statements together within a single block and sends the entire block to the server in a single call, therefore reducing network traffic.

Overview of PL/SQL

18Ć7

18Ć8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

PL/SQL Block Structure A basic PL/SQL block of code can contain up to three parts. The order in which the sections of the blocks are written is shown below. Section

Description

Inclusion

Declarative

Contains all variables, constants, cursors, and user-defined exceptions that will be referenced within the Executable section.

Optional

Executable

Contains SQL statements to manipulate data in the database and PL/SQL statements to manipulate data in the block.

Mandatory

Exception Handling

Specifies the actions to perform when errors and abnormal conditions arise within the Executable section.

Optional

Note: In PL/SQL, an error or warning is called an exception. Section keywords DECLARE, BEGIN, and EXCEPTION are not followed by semicolons. However, END and all other PL/SQL statements do require a semicolon to terminate the statement. You can string statements together on the same line. However, this method is not recommended for clarity or editing.

Overview of PL/SQL

18Ć9

18Ć10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

PL/SQL Block Structure

continued

Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely separate or nested one within another. Therefore, one block can represent a small part of another block, which in turn can be part of the whole unit of code. PL/SQL Program Constructs The following list outlines a variety of different PL/SQL program constructs using the basic PL/SQL block. They are available based on the environment where they are executed. Program Construct Anonymous Block

Description

Availability

Unnamed PL/SQL block that is embedded within an application or is issued interactively.

All PL/SQL environments.

Stored Procedure or Named PL/SQL block that can Function accept parameters and can be invoked repeatedly.

Oracle7 Server with Procedural Extension.

Application Procedure or Function

Named PL/SQL block that can accept parameters and can be invoked repeatedly.

Components of Developer/2000, for example Forms.

Package

Named PL/SQL module that Oracle7 Server with groups together related procedures, Procedural Extension. functions, and identifiers.

Database Trigger

PL/SQL block that is associated with a database table and is fired automatically.

Oracle7 Server with Procedural Extension.

Application Trigger

PL/SQL block that is associated with an application event and is fired automatically.

Components of Developer/2000, for example Forms.

Note: A function is similar to a procedure, except that a function must return a value.

Overview of PL/SQL

18Ć11

18Ć12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

PL/SQL Block Structure

continued

The two types of constructs covered in this course are anonymous blocks and subprograms. Anonymous Blocks Anonymous blocks are unnamed blocks. They are declared at the point in an application where they are to be executed and are passed to the PL/SQL engine for execution at runtime. You can embed an anonymous block within a precompiler program and within SQL*Plus or Server Manager. Triggers in Developer/2000 components consist of such blocks. Subprograms Subprograms are named PL/SQL blocks. You can declare them either as procedures or as functions. Procedures perform actions, and functions return values. Developer/2000 components allow you to declare procedures and functions as part of the application (a form or report), and call them from other procedures, functions, and triggers.

Overview of PL/SQL

18Ć13

18Ć14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The PL/SQL Environment PL/SQL is not an Oracle product in its own right; it is a technology employed by the Oracle7 Server and by certain Oracle tools. Blocks of PL/SQL are passed to and processed by a PL/SQL engine, which may reside within the tool or within the Oracle7 Server. The engine used depends on where the PL/SQL is being invoked. PL/SQL Engine at the Oracle7 Server When you submit blocks from a Pro* program, user-exit, SQL*Plus, or Server Manager, the PL/SQL engine in the Oracle7 Server processes them. It breaks the SQL within the block into separate statements and sends them to the SQL Statement Executor. This means that a single transfer is required to send the block from the application to the Oracle7 Server, thus improving performance especially in a client-server network. Stored subprograms can be referenced by any number of applications connected to the database. PL/SQL in Oracle Tools Many Oracle tools, including Developer/2000, have their own PL/SQL engine, which is independent of the engine present in the Oracle7 Server. The engine filters out SQL statements and sends them individually to the SQL Statement Executor in the Oracle7 Server. It processes the remaining procedural statements in the Procedural Statement Executor, which is within the PL/SQL engine. The Procedural Statement Executor processes data that is local to the application (that is already inside the client environment, rather than the database). This reduces work sent to the Oracle7 Server and the number of memory cursors required. Note: Procedures and functions declared as part of a Developer/2000 application are distinct from those stored in the database, although their general structure is the same. Stored subprograms are database objects and are stored in the Data Dictionary. They can be accessed by any number of applications. Application subprograms pass blocks to that application’s local PL/SQL engine. Work is done at the application site, not at the server site.

Overview of PL/SQL

18Ć15

18Ć16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

About Procedure Builder Oracle Procedure Builder is a tool you can use to create, execute, and debug PL/SQL programs used in your application tools, such as a form or a report, or on the Oracle7 Server through its graphical interface. Integrated PL/SQL Development Environment Procedure Builder’s development environment contains a built-in editor for you to create or edit subprograms. You can compile, test, and debug your code. Unified ClientĆServer PL/SQL Development Application partitioning through Procedure Builder is available to assist you with distribution of logic between client and server. Users can drag and drop a PL/SQL program unit between the client and the server.

Overview of PL/SQL

18Ć17

18Ć18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

19 Basics of Procedure Builder

Objectives

19Ć2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives A key feature of procedural programming is the ability to create and debug code quickly and easily. Procedure Builder provides all of the functionality necessary for you to successfully develop and debug PL/SQL programs. This lesson enables you to manipulate PL/SQL code using Procedure Builder. At the end of this lesson, you should be able to D

Identify the advantages of developing and debugging PL/SQL programs in Procedure Builder.

D

Manage program units by using the Object Navigator.

D

Execute program units and SQL statements by using the PL/SQL Interpreter.

D

Define and compile procedures by using the Program Unit editor.

D

Define and compile database procedures by using the Stored Program Unit editor.

D

Set a breakpoint to suspend program execution.

D

Control the execution of an interrupted PL/SQL program unit.

D

Test possible solutions by changing variables and procedures at runtime.

Basics of Procedure Builder

19Ć3

19Ć4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview Procedure Builder is an integrated development environment. It provides for the editing, compiling, testing, and debugging of PL/SQL programs within a single tool. In addition, it enables developers to drag and drop program units between the client and server. You can improve your application development efforts by using the features available in Procedure Builder. You will become familiar with these features by learning about each component’s function. Once you are familiar with the Procedure Builder environment, you will cover the PL/SQL syntax. Procedure Builder Features Component

Description

Object Navigator

Manage PL/SQL constructs. Perform debug actions.

PL/SQL Interpreter

Debug PL/SQL code. Evaluate PL/SQL code in real time.

Program Unit Editor

Create and edit PL/SQL source code.

Stored Program Unit Editor

Create and edit server-side PL/SQL source code.

Database Trigger Editor

Create and edit database triggers.

For more information, see Oracle Procedure Builder Developer’s Guide, Release 1.5.

Basics of Procedure Builder

19Ć5

Procedural Programming Capabilities

19Ć6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Oracle Procedure Builder Capabilities Procedure Builder is an integrated, interactive environment that you can use to create, execute, and debug PL/SQL programs. Using Procedure Builder, you can build portable database programs quickly and easily. Integrated PL/SQL Development Environment D

Create and edit subprograms.

D

Compile subprograms to perform syntactical error checking.

D

Test subprograms.

D

Debug subprograms.

Unified ClientĆServer PL/SQL Development D

Create database triggers.

D

Create stored procedures and move them to the client to debug.

D

Build and edit client-side libraries.

D

Create client-side program units and move them to the server.

Basics of Procedure Builder

19Ć7

Procedure Builder Components

Procedure Builder Components

19Ć8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Procedure Builder Components The Object Navigator The Object Navigator provides an outline style interface to browse objects, view the relationships between them, and edit their properties. The Interpreter The Interpreter is the central debugging workspace of Procedure Builder. It is a two-pane window where you display, debug, and run PL/SQL program units. It also interactively supports the evaluation of PL/SQL constructs, SQL commands, and Procedure Builder commands. The Program Unit Editor The easiest and most common place to enter PL/SQL source code is in the Program Unit editor. You can use it to edit, compile, and browse warning and error messages during application development. The Stored Program Unit Editor The Stored Program Unit editor is a GUI environment for editing server-side packages and subprograms. The compile operation submits the source text to the server-side PL/SQL compiler. To debug server-side program units you can drag a copy of the program unit to the client side using the Object Navigator. The Database Trigger Editor The Database Trigger editor is a GUI environment for editing database triggers. The compile operation submits the source text to the server-side PL/SQL compiler. Online Help Oracle Procedure Builder has a help facility that provides assistance at any time during your session. You can access it from the menu bar.

Basics of Procedure Builder

19Ć9

Using the Quick Tour

19Ć10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Procedure Builder Components

continued

Using the Quick Tour The Quick Tour, another type of online help, introduces you to product terminology, workflow, and theoretical concepts. This is an excellent resource to get started with Procedure Builder. You can invoke the Quick Tour by choosing the Quick Tour menu item from the Help menu. Procedure Builder Basics Become familiar with the Object Navigator to create and manage your PL/SQL objects. Also, learn the terminology used in the Object Navigator. Developing a Program Unit Review each step to develop a program unit. Create, edit, and compile a PL/SQL program unit using the Program Unit and Database Trigger editors. Debugging a Program Unit This section describes how to debug a program unit using the PL/SQL Interpreter. It describes how to set breakpoints, step through your code, and peruse the Stack node to change the value of the variable. Organizing PL/SQL Step through application partitioning between the client and server, including using libraries and moving subprograms between the client and server. Procedure Builder Features Review the kinds of application-building tasks you can perform using Procedure Builder.

Basics of Procedure Builder

19Ć11

Using Cue Cards

19Ć12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Procedure Builder Components

continued

Using Cue Cards Developer/2000 provides further help in the form of Cue Cards. Their purpose is to provide just-in-time coaching for frequently performed tasks. You can invoke Cue Cards by selecting the Cue Cards menu item from the Help menu. Cue cards contain two types of content: task and concept. Task cards list the steps to complete a task, while concept cards describe a particular concept with static graphics. When invoked, Cue Cards display a list of topics that are divided into two categories: D

Task: What would you like to do?

D

Concept: Learn About

To display the cue card for any of these topics, click the appropriate button to the left of the item. Cue Cards include a set of six buttons that you use to navigate to the information you require. Button

Action

Next Card

Advance one card.

Back

Return to the previous card.

Tell Me

Obtain more information about a topic.

Show Me

View a short movie or animation on a task.

Options

Set Cue Card options.

Exit

Exit Cue Cards.

Basics of Procedure Builder

19Ć13

The Object Navigator 1 5

5 4 2

3

4

1 Navigator drop down list

2 Subobject indicator

4 Object name

5 Find field

19Ć14

3 Type icon

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Object Navigator The Object Navigator provides immediate access to every object in your development environment. You can create and manipulate all of your PL/SQL program units, libraries, debug actions, and variables from the Object Navigator. Object Navigator Components Navigator Component

Description

Navigator drop down list

Indicates the name of the currently selected object.

Subobject indicator

Indicates whether an object can be expanded to view its subobjects.

Type icon

Indicates the object type.

Object name

Indicates the name of the object.

Find field

Used to search for a named object.

Basics of Procedure Builder

19Ć15

The Object Navigator Vertical Button Bar

1 2 3 4

1 Open/save

2 Cut/copy/paste

3 Create/delete

4 Expand/collapse/ expand all/collapse all

19Ć16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Object Navigator

continued

The Object Navigator Vertical Button Bar The Vertical Button Bar on the Object Navigator provides a convenient access for many of the actions frequently performed from the File, Edit, and Navigator menus. Elements of the Vertical Button Bar Element

Description

Open

Opens a library from the file system or from the Oracle7 Server.

Save

Saves a library on the file system or on the Oracle7 Server.

Cut

Cuts the selected object and stores it in the clipboard. Cutting an object also cuts any objects owned by that object.

Copy

Makes a copy of the selected object and stores it in the clipboard. Copying an object also copies any objects owned by that object.

Paste

Pastes the cut or copied module into the selected location. Note that objects must be copied to a valid location in the object hierarchy.

Create

Creates a new instance of the currently selected object.

Delete

Deletes the selected object with confirmation.

Expand

Expands the first level of subobjects of the currently selected object.

Collapse

Collapses the first level of subobjects of the currently selected object.

Expand All

Expands all levels of subobjects of the currently selected object.

Collapse All

Collapses all levels of subobjects of the currently selected object.

Basics of Procedure Builder

19Ć17

Objects of the Navigator

19Ć18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Object Navigator

continued

Object Navigator Objects By using the Object Navigator, you can display a hierarchical listing of all objects you have access to during your session. Object Node

Description

Program Units

PL/SQL construct that can be independently recognized and processed by the PL/SQL compiler.

Program Units – Specification

Name, parameter, and return type (functions only) of the program unit.

Program Units – References

Procedures, functions, anonymous blocks, and tables that the program unit references.

Program Units – Referenced By

Procedures, functions, anonymous blocks, and tables that reference the program unit.

Libraries

Collection of PL/SQL packages, procedures, and functions stored in the database or the file system.

Attached Libraries

Referenced libraries stored in the database or the file system.

Built-in Packages

PL/SQL constructs that can be referenced while debugging program units.

Debug Actions

Actions that enable you to monitor or interrupt the execution of PL/SQL program units.

Stack

Chain of subprogram calls, from the initial entry point down to the currently executing subprogram.

Database Objects

Collection of server-side stored program units, libraries, tables, and views.

Basics of Procedure Builder

19Ć19

19Ć20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Object Navigator

continued

Managing Objects Using the Object Navigator Use the Vertical Button Bar and the Find Field on the Object Navigator to manage PL/SQL constructs, debug actions, and database objects. Creating a Library 1.

Select the Libraries object.

2.

Click the Create button. The new library subobject will appear with a default name.

Saving a Library 1.

Select the Library to save.

2.

Select Save As from the File menu. The Save Library dialog box appears.

3.

Enter a new name for the library (optional). Choose either the File System or the Database radio button. Click the OK button to accept the options.

Expanding a Node 1.

Select a valid node.

2.

Click the Expand button or the Expand All button.

Searching for an Object 1.

Type the name, full or partial, of the object you wish to find in the Find Field. As soon as you begin typing, any match found starting from the top of the Object Navigator is highlighted.

2.

Click the Search Forward or Search Backward button to find additional matches of the search criteria in the Object Navigator.

Basics of Procedure Builder

19Ć21

The Interpreter

19Ć22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Interpreter Using the Interpreter, you can define, display, debug, and run PL/SQL program units. To display the Interpreter at any time, choose the PL/SQL Interpreter from the Tools menu. Interpreter Components Component

Description

Program execution buttons Enables you to execute the Step Into, Step Over, Step Out, Go, and Reset buttons. Close button

Closes the Interpreter.

Source pane

Displays a read-only copy of the program unit currently selected.

Interpreter pane

Provides a command line interface to PL/SQL and Procedure Builder.

Scroll bar

Scrolls the window.

Split bar

Changes the relative amount of space occupied by each pane in the Interpreter.

Executing a PL/SQL Procedure From the PL/SQL prompt in the Interpreter pane, enter the name of the procedure. Terminate the command with a semicolon. Syntax procedure_name [(argument1[, argument2, ...])];

Basics of Procedure Builder

19Ć23

The Interpreter Pane 1 2 3

1 Execute SQL DDL statements.

19Ć24

2 Create and execute an anonymous procedure.

3 Execute a SELECT statement.

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Interpreter

continued

The Interpreter Pane Using the Interpreter pane, you can interactively evaluate PL/SQL constructs and SQL commands. Executing SQL DDL Statements From the PL/SQL prompt in the Interpreter pane, enter SQL data definition language statements. To create the B_TEST table, enter the following statement: PL/SQL> CREATE TABLE b_test (col1 NUMBER);

Incremental Compilation of PL/SQL From the PL/SQL prompt in the Interpreter pane, enter PL/SQL statements. For example, to insert three rows into the B_TEST table, enter the following statement: PL/SQL> +> +> +> +> +> +>

PROCEDURE testproc IS BEGIN FOR i IN 1 ..3 LOOP INSERT INTO b_test VALUES (i); END LOOP; END;

Note: Details of the FOR loop will be covered in a later lesson. Executing SQL Statements From the PL/SQL prompt in the Interpreter pane, you can execute SQL statements. For example, to select all columns of the B_TEST table, enter the following statement: PL/SQL> SELECT * FROM b_test;

Basics of Procedure Builder

19Ć25

The Program Unit Editor 1 2

3

4

1 Compile and Source Text maintenance buttons

2 Name drop down list

3 Source Text pane

4 Compilation Message pane

19Ć26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Program Unit Editor Create, edit, and compile PL/SQL source code by using the Program Unit editor. Methods to Display the Program Unit Editor D

Choose Program Unit Editor from the Tools menu.

D

Double-click the icon of a program unit in the Object Navigator.

D

Select Program Units in the Object Navigator and click the Create button.

Program Unit Editor Components Component

Description

Compile button

Compiles the program unit appearing in the Source Text pane.

Apply button

Saves any changes made to the program unit in the editor since it was first opened or since the last apply or revert operation.

Revert button

Restores the state of the program unit to the last apply or revert.

New button

Invokes the New Program Unit dialog box.

Delete button

Deletes the current program unit (with confirmation).

Name drop down list

Displays the name and type of the current program unit. You can use the drop down list to select another program unit to edit.

Source Text pane

Allows you to enter and edit PL/SQL program unit source text.

Compilation Message pane

Displays error messages generated as a result of compilation.

Basics of Procedure Builder

19Ć27

Creating a Program Unit 1

2

1 Create the Program Unit.

19Ć28

2 Write the code.

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Program Unit Editor

continued

Creating a Program Unit 1.

Select the Program Units object or subobject.

2.

Click the Create button. The Program Unit dialog box appears.

3.

Enter a name and select a subprogram type radio button. Click the OK button to accept these entries. The Program Unit name appears in the Object Navigator.

4.

The Program Unit editor will be displayed. It contains the subprogram name, BEGIN, and END statements. The cursor is automatically positioned on the line beneath the BEGIN keyword.

Navigating Compilation Errors 1.

Click the Compile button in the Program Unit editor. Error messages generated during compilation are displayed in the Compilation Message pane.

2.

Click an error message. The text cursor positions at the location of the error in the Source Text pane.

Exporting a Program Unit to a Text File 1.

Open the Program unit so that it is displayed in the Program Unit editor.

2.

Select Export from the Edit menu. The Export to dialog box appears.

3.

Enter a name and directory location for the exported program unit text file. Click the OK button to accept these entries.

Program units that reside in the Program Units node are lost when you exit Procedure Builder.

Basics of Procedure Builder

19Ć29

The Stored Program Unit 4

1 2

3

1 Owner drop down list

2 Source Text pane

3 Compilation Message pane

4 Name drop down list

19Ć30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The Stored Program Unit Editor Create, edit, and compile server-side program units by using the Stored Program Unit editor. Visually and functionally, creating Stored Program Units in Procedure Builder is very similar to creating client-side Program Units. Connecting to the Oracle7 Server When initially invoked, Procedure Builder is a standalone session. To connect to a database, select Connect from the File menu, and enter the appropriate username, password, and database connection string. Methods to Display the Stored Program Unit Editor D

Choose Stored Program Unit Editor from the Tools menu.

D

Double-click the icon of a stored program unit in the Object Navigator.

Stored Program Unit Editor Components Component

Description

Owner drop down list

Displays usernames whose stored program units you can access.

Source Text pane

Allows you to enter and edit PL/SQL stored program unit source text.

Compilation Message pane

Displays error messages generated as a result of compilation.

Name drop down list

Displays a list of the owner’s stored program units.

Save button

Compiles and saves the program unit to the Oracle7 Server.

Basics of Procedure Builder

19Ć31

Debugging a Stored Program Unit

19Ć32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Debugging a Stored Program Unit Sometimes developers may not want to (or not have the privilege to) debug or refine a stored program unit in place on the server. In such cases, you may choose to drag a copy of the program unit to the client side. Debugging a Stored Program Unit 1.

Locate the appropriate stored program unit in the Object Navigator.

2.

Hold the mouse button down on the node of the program unit to be copied.

3.

Drag the mouse up to the Program Units object and release the mouse button. The selected stored program unit appears as a Program Units subobject.

4.

Perform debug actions.

5.

From the Object Navigator, select the debugged program unit subobject.

6.

Drag the mouse down to the same Stored Program Units Database Objects node and release the mouse button. The selected program unit appears as a Stored Program Units subobject.

Basics of Procedure Builder

19Ć33

Listing Code in the Source Pane 1 2

3

1 Source pane

19Ć34

2 Navigator pane

3 Interpreter pane

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Performing Debug Actions in the Interpreter You can use the Object Navigator to examine and modify parameters in an interrupted program. By invoking the Object Navigator within the Interpreter, you can perform debugging actions entirely within the Interpreter window. Alternatively, you can interact with the Object Navigator and Interpreter windows separately. Invoking the Object Navigator Pane 1.

Select PL/SQL Interpreter from the Tools menu to open the Interpreter if it is not already open.

2.

Select Navigator Pane from the View menu.

3.

The Navigator pane is inserted between the Source and the Interpreter panes.

4.

Drag the split bars to adjust the size of each pane.

Listing Source Text in the Source Pane 1.

Click the Program Units node in the Navigator pane to expand the list. The list of program units is displayed.

2.

Click the object icon of the program unit to be listed. The source code is listed in the Source pane of the Interpreter.

Basics of Procedure Builder

19Ć35

Setting a Breakpoint

1 2

1 Breakpoint

19Ć36

2 Debug action

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Setting a Breakpoint If you encounter errors while compiling or running your application, you should test the code and determine the cause of the error. To effectively determine the cause of the error, you step through the code, line by line. Eventually, you identify the exact line of code causing the error. One method to assist you is a breakpoint, which halts execution at any given point and permits you to examine the status of the code on a line-by-line basis. Setting a Breakpoint 1.

Double-click the executable line of code on which to break. A “B(n)” is placed in the line where the break is set.

2.

The message “Breakpoint #n installed at line i of name” is shown in the Interpreter pane.

Note: Breakpoints also can be set using debugger commands in the Interpreter pane. Test breakpoints by typing the program unit name at the Interpreter PL/SQL prompt. Monitoring Debug Actions Debug actions, like breakpoints, can be viewed in the Object Navigator under the heading Debug Actions. Double-click the Debug Actions icon to view a description of the breakpoint. Remove breakpoints by double-clicking the breakpoint line number.

Basics of Procedure Builder

19Ć37

Debug Commands

1 2

1 Trigger

19Ć38

2 Subprograms

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Setting a Breakpoint

continued

Stepping Through Code When a breakpoint is reached, you can use a set of commands to step through the code. You can execute these commands by clicking the command buttons on the Interpreter toolbar or by entering the command at the Interpreter prompt. Commands to Step Through Code Command

Description

Step Into

Advances execution into the next executable line of code.

Step Over

Bypasses the next executable line of code and advances to the subsequent line.

Step Out

Resumes to end of current level of code, such as the subprogram.

Go

Resumes execution until either the program unit ends or is interrupted again due to a debug action.

Reset

Aborts execution at the current debug levels.

Basics of Procedure Builder

19Ć39

Stepping Through Code 1 2

3

1 Command buttons

19Ć40

2 Breakpoint

3 Debug message

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Setting a Breakpoint

continued

Determining the Cause of Error Once the breakpoint is found at runtime, you can begin stepping through the code. An arrow (=>) indicates the line of code to execute. 1.

Click the Step Into button. A single line of code is executed. The arrow moves to the next line of code.

2.

Repeat step 1 as necessary until the line causing the error is found. The arrow continues to move forward until the erroneous line of code is found. At that time, PL/SQL displays an error message.

Basics of Procedure Builder

19Ć41

Changing a Value

4

1 2

3

1 Click the Stack node

2 Click the variable value

3 Enter the new value

4 Click the Go button

19Ć42

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Examining Local Variables Using Procedure Builder, you can examine and modify local variables and parameters in an interrupted program. The Stack node in the Navigator pane is where you can view and change the values of local variables and parameters associated with the current program unit located in the Call Stack. When debugging code, check for the absence of values as well as incorrect values. Examining Values and Testing the Possible Solution 1.

Click the Stack node in the Object Navigator or Navigator pane to expand it.

2.

Click the value of the variable to edit. For example, select variable 1. The value “1” becomes an editable field.

3.

Enter the new value and click anywhere in the Navigator pane to end the variable editing, for example, enter “3”. The following statement is displayed in the Interpreter pane. (debug1)PL/SQL> debug.seti(’I’,3);

4.

Click the Go button to resume execution through the end of the program unit.

Note: Variables and parameters can also be changed using commands at the Interpreter PL/SQL prompt.

Basics of Procedure Builder

19Ć43

Summary

19Ć44

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary There are clear advantages to developing and debugging PL/SQL programs in Procedure Builder: Application Partitioning D

Manage program units using the Object Navigator.

D

Move program units between client and server.

Editors D

Create and compile procedures by using the Program Unit editor.

D

Create and compile database procedures by using the Store Program Unit editor.

Execution Environment D

Execute program units by using the PL/SQL Interpreter.

Debugging D

Suspend program execution by using breakpoints.

D

Step through code to determine the location of the error.

D

Examine local variables to determine the cause of the error.

D

Modify variable values to test possible solutions at runtime.

Basics of Procedure Builder

19Ć45

Practice Overview

19Ć46

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview This practice will familiarize you with the Procedure Builder environment and windows. Practice Contents D

Exploring Procedure Builder menus and windows

D

Creating a program unit

D

Executing a program unit

Basics of Procedure Builder

19Ć47

19Ć48

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 19 1.

Load and execute a loop counter. a.

Launch Procedure Builder. Your instructor will give you the login information.

b.

From the menu, load the LABS\p19loop.pls file.

c.

Execute the procedure from the Interpreter pane. Pass a numeric value into the procedure as demonstrated below. Reminder: The Cue Cards can help you get started. PL/SQL> count_loops(4);

2.

Create, compile, and execute a procedure. a.

Create a procedure named MY_MESSAGE as demonstrated below: PROCEDURE my_message IS BEGIN TEXT_IO.PUT_LINE (’Hello World’); END;

b.

Compile the procedure using the Program Unit Editor.

c.

Execute the procedure from the Interpreter pane.

PL/SQL> my_message;

Basics of Procedure Builder

19Ć49

19Ć50

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

20 Modularizing Programming with Subprograms

20Ć2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives Modularity allows you to break your code into manageable, well-defined logical units. Each of these units in PL/SQL is called a program unit, or a subprogram. PL/SQL has two types of subprograms called procedures and functions. This lesson covers the structure of subprograms and how to invoke them. At the end of this lesson, you should be able to D

Determine the types of program units and where to use them.

D

Explain the differences between and benefits of procedures and functions.

D

Develop subprograms.

D

Invoke subprograms from Procedure Builder.

Modularizing Programming with Subprograms

20Ć3

20Ć4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview Program units are named PL/SQL blocks. They fall into three main categories: D

Procedures to perform actions

D

Functions to compute a value

D

Packages to bundle logically related procedures and functions

Stored or Application Subprogram? These program units can be created in a variety of environments, including server-side stored subprograms or as application subprograms. Concept

Stored Subprogram

Application Subprogram

Location

Is in the database.

Is within the application.

Executed

From any database tool or application.

From only the application in which it was created.

Availability

By way of database security.

Independently of, and in addition to, stored subprograms.

Subprograms are composed of a number of sections: D

A header to name and type the block

D

An optional declarative section to set up local identifiers

D

An executable part to perform the actions

D

An optional exception handling section to handle exceptions

For more information, see PL/SQL User’s Guide and Reference, Release 2.3, “Subprograms.”

Modularizing Programming with Subprograms

20Ć5

20Ć6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Subprogram The following steps will assist you to create a subprogram. 1.

Select your environment. If using Procedure Builder, then select either the Program Units node or the Database Objects node and Stored Procedures Units subobject node.

2.

Write your syntax. If using Procedure Builder, enter the syntax in the Program Unit Editor. If using SQL*Plus, write your code in a text editor as a script file.

3.

Compile your code. The source code is complied into p-code. If using Procedure Builder, click the Compile button. If using SQL*Plus, start your file at the SQL prompt.

4.

Invoke the successfully compiled procedure or function.

Guidelines D

SQL*Plus is another development environment for writing and for initial testing of a procedure, although you will need to test the procedure by invoking it from an application.

D

The SQL commands issued to create a stored subprogram are CREATE PROCEDURE or CREATE FUNCTION.

D

The SQL commands issued to remove a stored subprogram are DROP PROCEDURE or DROP FUNCTION.

D

Use CREATE OR REPLACE PROCEDURE or CREATE OR REPLACE FUNCTION so you do not have to issue a DROP statement.

Modularizing Programming with Subprograms

20Ć7

20Ć8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Procedure Create a PL/SQL procedure to store a series of actions for later execution. The procedure can contain zero or more parameters, which are arguments that you list when calling the procedure. Syntax PROCEDURE name [(parameter,...)] IS pl/sql_block; where: name

is the procedure name, which adheres to the standard Oracle naming rules.

parameter

is the parameter syntax shown below.

pl/sql_block

is the procedural body that defines the action performed by the procedure.

The parameter syntax is as follows. Syntax parameter_name [IN | OUT | IN OUT] datatype [{:= | DEFAULT} expr] where: parameter_name

is the name of the parameter.

datatype

is the datatype of the parameter, without constraints.

expr

is the value to initialize the parameter.

Guidelines D

Start the PL/SQL block with the keyword IS.

D

Enter any local declarations between IS and BEGIN.

When creating the procedure from Procedure Builder, the CREATE OR REPLACE portion of the syntax is implied. Therefore, when creating the procedure from SQL*Plus, begin the statement with CREATE OR REPLACE.

Modularizing Programming with Subprograms

20Ć9

20Ć10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Procedure

continued

Procedural Parameters Transfer values to and from the calling environment through parameters. There are two types that you use. When declaring a procedure, the formal parameter is used to define the values used in the executable portion of the PL/SQL block. The actual parameter, or argument, is referenced when invoking a subprogram. Parameter Modes for Formal Parameters Parameter Mode

Description

IN

Default argument. Passes a value from the calling environment into the subprogram. Formal parameter acts as a constant—you cannot overwrite the value. Actual parameter can be an expression, a constant, a literal, or an initialized variable.

OUT

Must be specified. Returns a value from the procedure to the calling environment. Formal parameter acts as an uninitialized variable. Formal parameter cannot be assigned to another variable or to itself. Actual parameter must be a variable; it cannot be a constant or expression.

IN OUT

Must be specified. Passes a value from the calling environment into the procedure, and returns a possibly different value from the procedure to the calling environment. Formal parameter acts as an initialized variable. Formal parameter can be used as a normal variable; it can be assigned to a value. Actual parameter must be a variable.

Modularizing Programming with Subprograms

20Ć11

20Ć12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Procedure

continued

Example Update the salary of the specified employee to the specified amount through a procedure. PROCEDURE change_salary (v_emp_id IN NUMBER, -- formal parameters v_new_salary IN NUMBER) IS BEGIN -- begin PL/SQL block UPDATE s_emp SET salary = v_new_salary WHERE id = v_emp_id; COMMIT; END change_salary; This procedure, when invoked, will take the parameters for the employee number and the new salary, and update the salary for that specified employee. The content of the PL/SQL block will be covered in the lesson “Developing a Simple PL/SQL Block.” Eliminate Unnecessary IN Arguments D

Where possible, derive values in the procedure, or use column default values.

D

Generate the primary key using a database sequence.

D

Record the username from the USER function.

D

Record the current date from the SYSDATE function.

D

Take advantage of business rules to compute input values automatically using a formula.

Modularizing Programming with Subprograms

20Ć13

20Ć14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Comparing Functions and Procedures A procedure can contain a list of parameters, but does not have to return a value. It is invoked in place of a complete PL/SQL statement. A function differs from a procedure in two ways: D

You invoke the function as part of an expression.

D

A function must return a value.

SQL Functions There are both user-defined functions, covered in this lesson, and SQL functions. You are already familiar with SQL functions. You call the function with actual parameters from within a SQL command, such as SELECT. -- Example Number Functions ROUND (1896,2) TRUNC (1892,-2) -- Example Group Functions SUM (s_emp.salary) AVG (s_ord.total) -- Other System Functions USER -- username SYSDATE -- current date and time s_dept_id.NEXTVAL -- database sequence value A procedure containing one OUT argument can be rewritten as a function containing a RETURN statement.

Modularizing Programming with Subprograms

20Ć15

20Ć16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Function Create a PL/SQL function to return a value to the calling environment. You must declare the RETURN datatype in the header section of the function definition, and define the value to be returned in the PL/SQL block. You can also declare a list of parameters to be passed into the function. Syntax FUNCTION name [(parameter,...)] RETURN datatype IS pl/sql_block; where: name

is the function name, which adheres to the standard Oracle naming rules.

parameter

is the parameter syntax. See the syntax in the “Procedure” section of this lesson.

datatype

is the datatype of the value to be returned.

pl/sql_block

is the procedural body that defines the action performed by the procedure.

The RETURN Statement Remember to include a RETURN statement in the PL/SQL block. The function must set the value of the return parameter and be of the same datatype specified in the RETURN clause of the function definition. Multiple RETURN statements are allowed, but only one will be executed by any one call. Typically, the multiple RETURN statements are within an IF statement. When creating the function from Procedure Builder, the CREATE OR REPLACE portion of the syntax is implied. Therefore, when creating the function from SQL*Plus, begin the statement with CREATE OR REPLACE.

Modularizing Programming with Subprograms

20Ć17

20Ć18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Function

continued

Example Return the tax based on the value parameter in a function. FUNCTION tax (v_value IN NUMBER) RETURN NUMBER IS BEGIN RETURN (v_value * .07); END tax; Avoid using the OUT and IN OUT modes with functions. Functions are designed to return a single value.

Modularizing Programming with Subprograms

20Ć19

20Ć20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Invoking Subprograms You can call procedures and functions from any tool or language that supports PL/SQL. From PL/SQL, you can call a procedure with a direct call, and call a function as part of an expression. Invoking Procedures from Procedure Builder Enter the procedure name with any actual parameters, if applicable, at the Procedure Builder Interpreter prompt. Procedure Builder then performs the action specified in the procedure. Example Use the CHANGE_SALARY procedure to change the salary to 1000 for employee number 17. PL/SQL> change_salary (17, 1000); Note: You may want to confirm the changes by issuing a SELECT statement. Invoking Procedures from Another Procedure The example on the facing page illustrates how you can invoke a procedure from another procedure. In the example, procedure CHANGE_SALARY is being invoked from procedure PROCESS_SAL. Similarly, you can invoke a function from a stored procedure or a PL/SQL anonymous block. To invoke procedures from SQL*Plus, use the EXECUTE command. Use SQL*Plus bind variables to hold returned values. You can also use SQL*Plus substitution variables through the ampersand (&) and variable name.

Modularizing Programming with Subprograms

20Ć21

20Ć22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Invoking Subprograms

continued

Invoking Standalone Functions You can invoke a standalone function created in Procedure Builder. First, you must create a variable called the “identifier” to hold the returned value. Syntax CREATE variable where: variable is one of the following: NUMBER var_name [PRECISION number] [SCALE number]

Specifies a variable, var_name, of the datatype NUMBER. PRECISION determines the maximum number of objects. SCALE determines where rounding should occur.

DATE var_name

Specifies a variable, var_name, of the datatype DATE.

CHAR var_name [LENGTH number]

Specifies a variable, var_name, of the datatype CHAR with an optional length setting in bytes.

After creating the variable, you execute the function. Finally, you view the variable value. Example Display the tax based on a value. Use the TAX function created earlier. PL/SQL> .CREATE NUMBER x PRECISION 4 PL/SQL> :x := tax(100); PL/SQL> TEXT_IO.PUT_LINE (TO_CHAR(:x)); 7 For more information, see Procedure Builder Developer’s Guide, “Working with PL/SQL Constructs.” Note: To invoke functions from SQL*Plus, use the EXECUTE command. Use SQL*Plus global variables to hold returned values. You can also use SQL*Plus substitution variables through the ampersand (&) and variable name. To view the result, use the SQL*Plus PRINT command.

Modularizing Programming with Subprograms

20Ć23

20Ć24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Invoking Subprograms

continued

Invoking Functions in SQL Statements You can also call functions in SQL expressions. Anywhere a built-in SQL function can be placed, a PL/SQL user-defined function can be placed as well. Advantages D

Permit calculations that are too complex, awkward, or unavailable with SQL.

D

Increase efficiency of queries by performing functions in the server rather than in an application.

Note: This feature is only available with PL/SQL 2.1 or higher and Oracle7 Server release 7.1 or higher. Guidelines D

Only stored functions can be called from SQL statements, procedures cannot.

D

The function acts as a single-row function.

D

The function cannot contain a DML statement—the function cannot modify database tables.

D

All formal parameters must be IN parameters; none can be an OUT or IN OUT parameter.

D

Datatypes used in the function must be Oracle7 Server internal datatypes, such as CHAR and DATE, not PL/SQL datatypes, such as BOOLEAN or RECORD.

D

The RETURN datatype must be an Oracle7 Server internal datatype.

D

You must own or have EXECUTE privileges on the PL/SQL function in order to call it.

Modularizing Programming with Subprograms

20Ć25

20Ć26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Invoking Subprograms

continued

Calling a Function You can call functions from any of these SQL clauses. D

The select list of a SELECT command

D

The condition of a WHERE and HAVING clause

D

The CONNECT BY, START WITH, ORDER BY, and GROUP BY clauses

D

The VALUES clause of the INSERT command

D

The SET clause of the UPDATE command

Example Use the TAX function to calculate the tax on the total sale for order number 100. PL/SQL> SELECT total, tax(total) +> FROM s_ord +> WHERE id = 100; TOTAL TAX(TOTAL) ------------- ---------601100.00 42077

Modularizing Programming with Subprograms

20Ć27

20Ć28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary D

D

D

D

Subprograms fall into three main categories: D

Procedures to perform actions

D

Functions to compute a value

D

Packages to bundle logically related procedures and functions

A function differs from a procedure in two ways: D

You invoke the function as part of an expression.

D

A function must return a value.

Procedure and function components: D

Header—To name and type the block

D

Declarative—To set up local identifiers (optional)

D

Executable—To perform the actions

D

Exception handling—To handle exceptions (optional)

Invoke subprograms from the Procedure Builder Interpreter prompt.

Modularizing Programming with Subprograms

20Ć29

20Ć30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview This practice guides you through creating a simple procedure and function and invoking those functions from the Interpreter prompt. Practice Contents D

Creating a simple procedure

D

Debugging the procedure

D

Executing the procedure

Note: You use the TEXT_IO built-in package in this procedure to print a result at the Interpreter prompt.

Modularizing Programming with Subprograms

20Ć31

20Ć32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 20 1.

A procedure can contain IN, OUT, and IN OUT parameters. True / False

2.

A procedure can be used in a SQL statement. True / False

3.

The IN OUT argument mode is the default mode. True / False

4.

Functions are executed as part of an expression. True / False

5.

Name the four parts of the subprogram syntax. a. b. c. d.

6.

Create a procedure called MY_PROCEDURE to output the phrase “My Procedure Works” to the screen. a.

Replace the skeleton text with text from LABS/p20proc.pls.

b.

Compile the code. Make appropriate corrections so code successfully compiles.

c.

Execute the procedure at the Interpreter prompt.

Modularizing Programming with Subprograms

20Ć33

20Ć34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

21 Developing a Simple PL/SQL Block

21Ć2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives In this lesson, you create a simple PL/SQL block after learning the various elements that compose a block. At the end of this lesson, you should be able to D

Declare and use variables and constants in PL/SQL.

D

Assign new values to variables within the executable section.

D

Create and execute a named PL/SQL subprogram in Procedure Builder.

Developing a Simple PL/SQL Block

21Ć3

21Ć4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview A PL/SQL block is comprised of up to three sections: declarative (optional), executable (required), and exception handling (optional). Only BEGIN and END keywords are required. Each subprogram contains an additional section, the header (required). You can store and change values within a PL/SQL block by declaring and referencing variables and other identifiers. Handling Variables D

Declare and initialize variables within the declaration section.

D

Assign new values to variables within the executable section.

D

Pass values into PL/SQL blocks through parameters.

D

View the results from a PL/SQL block through output variables.

Note: The END keyword can be optionally followed by the name of the subprogram for clarity.

Developing a Simple PL/SQL Block

21Ć5

21Ć6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring PL/SQL Variables and Constants You need to declare all identifiers within the declaration section before referencing them within the PL/SQL block. Syntax identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; where: identifier

is the name of the identifier.

CONSTANT

constrains the identifier so that its value cannot change; constants must be initialized.

datatype

is a scalar or composite datatype.

NOT NULL

constrains the variable so that it must contain a value; NOT NULL variables must be initialized.

expr

is any PL/SQL expression that can be a literal, another variable, or an expression involving operators and functions.

Guidelines D

Name the identifier according to the same rules used for SQL objects.

D

You can use naming conventions, for example v_name to represent a variable, and c_name to represent a constant.

D

You have the option of assigning an initial value to variables, unless they are NOT NULL.

D

Initialize the variable to an expression with the assignment operator (:=), or, equivalently, with the DEFAULT reserved word; otherwise, variables are initialized to NULL by default.

D

Declare at most one identifier per line.

For more information, see PL/SQL User’s Guide and Reference, Release 2.3, “Datatypes.”

Developing a Simple PL/SQL Block

21Ć7

21Ć8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring Scalar Variables PL/SQL supports three datatypes—scalar, composite, and reference—that you can use for declaring variables, constants, and pointers. Scalar Datatypes A scalar datatype holds a single value and has no internal components. Scalar datatypes can be classified into four categories: number, character, date and time, or Boolean. Character and number datatypes have subtypes that associate a base type to a constraint. For example, INTEGER and POSITIVE are subtypes of the NUMBER base type. Datatype

Description

BINARY_INTEGER

Base type for integers between –2147483647 and 2147483647.

NUMBER [(precision,scale)]

Base type for fixed and floating point numbers.

CHAR [(maximum_length)]

Base type for fixed length character data up to 32767 bytes. If you do not specify a maximum_length, the default length is set to 1.

LONG

Base type for variable length character data up to 32760 bytes.

LONG RAW

Base type for binary data up to 32760 bytes.

VARCHAR2(maximum_length)

Base type for variable length character data up to 32767 bytes.

DATE

Base type for dates and times.

BOOLEAN

Base type that stores one of three possible values used for logical calculations: TRUE, FALSE, or NULL.

Note: The above list is abridged. For the complete list, see the PL/SQL User’s Guide and Reference, Release 2.3, “Datatypes.”

Developing a Simple PL/SQL Block

21Ć9

21Ć10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring Scalar Variables

continued

Examples Declare a variable to store the gender code (M or F). v_gender

CHAR(1);

Declare a variable to count the iterations of a loop and initialize the variable to 0. v_count

BINARY_INTEGER := 0;

Declare a variable to accumulate the total salary for a department and initialize the variable to 0. v_total_sal

NUMBER(9,2) := 0;

Declare a variable to store the ship date of an order, and initialize the variable to one week from today. v_order_date

DATE := SYSDATE + 7;

Declare a constant for the tax rate, which never changes throughout the PL/SQL block. c_tax_rate

CONSTANT NUMBER(3,2) := 8.25;

Declare a flag to indicate whether a piece of data is valid or invalid, and initialize the variable to TRUE. v_valid

BOOLEAN NOT NULL := TRUE;

Developing a Simple PL/SQL Block

21Ć11

21Ć12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring Scalar Variables

continued

The %TYPE Attribute When you declare PL/SQL variables to hold column values, you must ensure that the variable is of the correct datatype and precision. If it is not, then a PL/SQL error will occur during execution. Rather than hard-coding the datatype and precision of a variable, you can declare a variable according to another previously-declared variable or database column. You do this using the %TYPE attribute. To use the attribute in place of the datatype required in the variable declaration, prefix it with the database table and column names. If referring to a previously-declared variable, prefix the variable name to the attribute. PL/SQL determines the datatype and size of the variable when the block is compiled, so the variable is always compatible with the database column or identifier used to populate the variable. Advantages of Using the %TYPE Attribute D D

The datatype of the underlying database column may be unknown. The datatype of the underlying database column may change at runtime.

Examples Declare variables to store the first and last names for an employee. ... v_last_name v_first_name ...

s_emp.last_name%TYPE; s_emp.first_name%TYPE;

Declare variables to store the balance for a checking account, as well as the minimum balance, which starts out as 10. ... v_balance NUMBER(7,2); v_minimum_balance v_balance%TYPE := 10; ... A NOT NULL column constraint does not apply to variables declared using %TYPE. Therefore, if you declare a variable using the %TYPE attribute using a database column defined as NOT NULL, you can assign the NULL value to the variable.

Developing a Simple PL/SQL Block

21Ć13

21Ć14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring Composite Datatypes A composite datatype contains internal components and is reusable. Two types of composite datatypes are available in PL/SQL: TABLE and RECORD. PL/SQL Table D

A PL/SQL TABLE datatype is not the same as a database table.

D

A PL/SQL TABLE is similar to a one-dimensional array.

D

A PL/SQL TABLE must contain two components:

D

D

A primary key of datatype BINARY_INTEGER that indexes the PL/SQL TABLE.

D

A column of a scalar datatype, which stores the PL/SQL TABLE elements.

A PL/SQL TABLE can increase dynamically because it is unconstrained.

Developing a Simple PL/SQL Block

21Ć15

21Ć16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring Composite Datatypes

continued

Declaring PL/SQL Tables 1.

Declare a TABLE datatype.

2.

Declare a variable of that datatype.

Syntax TYPE type_name IS TABLE OF scalar_datatype [NOT NULL] INDEX BY BINARY_INTEGER; identifier type_name; where: type_name

is the name of the TABLE type.

scalar_datatype

is the datatype of the PL/SQL TABLE elements. You can use the %TYPE attribute.

identifier

is the name of the identifier.

Example Declare PL/SQL TABLE variables to store the first name and last name. ... TYPE name_table_type IS TABLE OF VARCHAR2(25) INDEX BY BINARY_INTEGER; first_name_table name_table_type; last_name_table name_table_type; ... The NOT NULL constraint prevents nulls from being assigned to the PL/SQL TABLE of that type. Do not initialize the PL/SQL TABLE.

Developing a Simple PL/SQL Block

21Ć17

21Ć18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring Composite Datatypes

continued

PL/SQL RECORD D

A PL/SQL RECORD datatype is not the same as a row in a database table.

D

A PL/SQL RECORD is similar in structure to a record in a 3GL.

D

A PL/SQL RECORD must contain one or more components of any scalar, RECORD, or PL/SQL TABLE datatype called fields. These uniquely named fields can have different datatypes.

D

The PL/SQL RECORD allows you to treat this collection of fields as one logical unit.

D

PL/SQL RECORDS are convenient for fetching a row of data from a table for processing in a PL/SQL block.

Developing a Simple PL/SQL Block

21Ć19

21Ć20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring Composite Datatypes

continued

Declaring PL/SQL Records 1.

Declare a RECORD datatype.

2.

Declare a variable of that datatype.

Syntax TYPE type_name IS RECORD (field_name1 field_type [NOT NULL {:=|DEFAULT} expr], (field_name2 field_type [NOT NULL {:=|DEFAULT} expr], ...); identifier type_name; where: type_name

is the name of the RECORD type.

field_name

is the name of the field.

field_type

is the datatype of the field. You can use the %TYPE and %ROWTYPE attribute.

expr

is any PL/SQL expression that can be a literal, another variable, or an expression involving operators and functions.

identifier

is the name of the identifier.

Example Declare variables to store first name, last name, and gender of a new employee. ... TYPE emp_record_type IS RECORD (last_name VARCHAR2(25), first_name VARCHAR2(25), gender CHAR(1)); employee_record emp_record_type; ... The NOT NULL constraint prevents the assigning of nulls to those fields. Be sure to initialize NOT NULL fields.

Developing a Simple PL/SQL Block

21Ć21

21Ć22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring Composite Datatypes

continued

Declaring Records with the %ROWTYPE Attribute Declare a record based upon a collection of columns in a database table or view by using the %ROWTYPE attribute. The fields within the record take their names and datatypes from the columns of the table or view. Advantages of Using the %ROWTYPE Attribute D

The number and datatypes of the underlying database columns may be unknown.

D

The number and datatypes of the underlying database columns may change at runtime.

D

Useful when retrieving a row with the SELECT statement.

Example Declare a variable to store the same information about a department as it is stored in the S_DEPT table. ... dept_record ...

s_dept%ROWTYPE;

This declaration creates a record with the same field names and field datatypes as a row in a table. DEPT_RECORD is a record. The fields are: DEPT_RECORD.ID, DEPT_RECORD.NAME, and DEPT_RECORD.REGION_ID.

Developing a Simple PL/SQL Block

21Ć23

21Ć24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

PL/SQL Block Syntax Rules Because PL/SQL is an extension of SQL, the general syntax rules that apply to SQL are also applicable to the PL/SQL language. Guidelines D

Identifiers can contain up to 30 characters, but they must start with an alphabetic character.

D

Reserved words cannot be used as identifiers unless they are enclosed within double quotation marks (for example, “SELECT”).

D

Do not choose the same name for the identifier as the name of columns in a table used in the block. If PL/SQL identifiers are in the same SQL statements and have the same name as a column, then Oracle assumes that it is the column that is being referenced.

D

Statements can be split across lines, but keywords must not be split.

D

Lexical units (for example, identifiers or literals) can be separated by one or more spaces or other delimiters that cannot be confused as being part of the lexical unit.

D

Character and date literals must be enclosed within single quotation marks.

D

Numeric literals can be represented by either a simple value (for example, –32.5) or by scientific notation (for example, 2E5, meaning 2x10 to the power of 5 = 200000).

D

Multiple line comments can be enclosed by /* and */ symbols. A single line comment begins with --, and the end-of-line marks the comment’s end.

For more information, see PL/SQL User’s Guide and Reference, Release 2.3, “Appendix E” for a list of reserved words.

Developing a Simple PL/SQL Block

21Ć25

21Ć26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

PL/SQL Block Syntax Rules

continued

Nested Blocks One of the advantages PL/SQL has over SQL is the ability to nest statements. You can nest blocks wherever an executable statement is allowed, thus making the nested block a statement. Therefore, you can break down the executable part of a block into smaller blocks. The exception section can also contain nested blocks. Variable Scope The scope of an object is the region of the program that can refer to the object. You can reference the declared variable within the executable section. An identifier is visible in the block in which it is declared and all nested sub-blocks, procedures, and functions. If the block does not find the identifier declared locally, it looks up to the declarative section of the enclosing (or parent) blocks. The block never looks down to enclosed (or child) blocks or sideways to sibling blocks. Scope applies to all declared objects, including variables, cursors, user-defined exceptions, and constants.

Developing a Simple PL/SQL Block

21Ć27

21Ć28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Assigning Values to Variables To assign or reassign a value to a variable, you write a PL/SQL assignment statement. You must explicitly name the variable to receive the new value to the left of the assignment operator (:=). Syntax identifier := expr;

plsql_table_name(primary_key_value) := expr;

plsql_record_name.field_name := expr; where: identifier

is the name of the identifier.

plsql_table_name

is the name of the PL/SQL TABLE.

primary_key_value

is the binary integer value that is the index of the PL/SQL TABLE and could also be a variable.

plsql_record_name

is the name of the PL/SQL RECORD.

field_name

is the field from the PL/SQL RECORD.

expr

can be a variable, constant, literal, or function call, but not a database column.

Developing a Simple PL/SQL Block

21Ć29

21Ć30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Assigning Values to Variables

continued

Examples Set the maximum salary identifier V_MAX_SAL to the value of current salary identifier V_SAL. v_max_sal

:= v_sal;

Store the name “Maduro” in the index identifier of 3 in the PL/SQL TABLE of last names. last_name_table (3) := ’Maduro’; Store basic information for a new employee in a PL/SQL RECORD. emp_record.last_name emp_record.first_name emp_record.gender

:= ’Maduro’; := ’Elena’; := ’F’;

Set the salary to the salary from the S_EMP table. This example produces a compile error. v_sal

:= s_emp.salary;

Remember that string literals must be enclosed with single quotation marks, for example, ’Hello, world’. If there is a single quotation mark in the string, write a single quotation mark twice, for example, ’Account wasn’’t found’.

Developing a Simple PL/SQL Block

21Ć31

21Ć32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Assigning Values to Variables

continued

Class Exercise Evaluate the PL/SQL block on the opposite page. Determine each of the following values according to the rules of scoping. 1.

The value of V_WEIGHT within the sub-block.

2.

The value of V_NEW_LOCN within the sub-block.

3.

The value of V_WEIGHT within the main block.

4.

The value of V_MESSAGE within the main block.

5.

The value of V_NEW_LOCN within the main block.

Developing a Simple PL/SQL Block

21Ć33

21Ć34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Assigning Values to Variables

continued

Operators The logical, arithmetic, and concatenation operators used in PL/SQL are the same as those in SQL. In addition, there is an exponential operator (**). You can control the order in which operations are performed by using parentheses, as in SQL. Examples Increment the index for a loop. v_count

:= v_count + 1;

Set the value of a Boolean flag depending upon whether two numbers are equal. v_equal

:= (v_n1 = v_n2);

Validate an employee number if it contains a value. v_valid

:= (v_emp_id IS NOT NULL);

Developing a Simple PL/SQL Block

21Ć35

21Ć36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Assigning Values to Variables

continued

Functions Most of the functions available in SQL are also valid in PL/SQL expressions: D

Single-row number functions

D

Single-row character functions

D

Datatype conversion functions

D

Date functions

D

Miscellaneous functions

Functions not available in procedural statements: D

GREATEST and LEAST

D

Group functions: AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCE

Group functions apply to groups of rows in a table, and are therefore available only within SQL statements in a PL/SQL block. Examples Build the mailing address for a company. v_mailing_address := v_name||CHR(10)||v_address|| CHR(10)||v_country||CHR(10)||v_zip_code; Convert the name to uppercase. v_last_name

:= UPPER (v_last_name);

Compute the sum of all numbers stored in the NUMBER_TABLE PL/SQL table. This example produces a compile error. v_total

:= SUM(number_table);

CHR is the SQL function that converts an ASCII code to its corresponding character; 10 is the code for a line feed.

Developing a Simple PL/SQL Block

21Ć37

21Ć38

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Assigning Values to Variables

continued

Datatype Conversion Within an expression, you should make sure that datatypes are the same. If mixed datatypes occur in the same expression, you should use the appropriate conversion function from the list below to convert the data. Syntax TO_CHAR (value, fm)

TO_DATE (value, fm)

TO_NUMBER (value, fm) where: value

is a character string, number, or date.

fm

is the format model used to convert value.

Examples Store a value that is composed of the user name and today’s date. This code causes a syntax error. v_comment

:= USER||’: ’||SYSDATE;

To correct the error, convert SYSDATE to a character string with the TO_CHAR conversion function. v_comment

:= USER||’: ’||TO_CHAR(SYSDATE);

PL/SQL will attempt conversion if possible, but the success will depend upon the operations being performed. It is good programming practice to explicitly perform datatype conversions because they can favorably affect performance and remain valid even with a change in software versions.

Developing a Simple PL/SQL Block

21Ć39

21Ć40

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Assigning Values to Variables

continued

Referencing NonĆPL/SQL Variables You can reference variables declared in the host or calling environment in PL/SQL statements, unless the statement is within a procedure, function, or package. This includes host language variables declared in precompiler programs, screen fields in a Developer/2000 Forms application, and SQL*Plus bind variables. To reference host variables, you must prefix the references with a colon (:) to distinguish them from declared PL/SQL variables. Example Store the annual salary in a SQL*Plus global variable. :g_annual_ salary

:= v_salary * 12;

Developing a Simple PL/SQL Block

21Ć41

21Ć42

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Programming Guidelines Adhere to programming guidelines for producing clear code and reducing maintenance when developing a PL/SQL block. Guidelines D

Document code with comments.

D

Develop case conventions for the code.

D

Develop naming conventions for identifiers and other objects.

D

Indent code to enhance readability.

Commenting Code Comment code to document each phase and to assist with debugging. Comment the PL/SQL code with two dashes (--) if the comment is on a single line, or enclose the comment between the symbols /* and */ if the comment spans several lines. Example Compute the yearly salary from the monthly salary. ... v_sal NUMBER(9,2); BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_sal := v_sal*12; END;

Developing a Simple PL/SQL Block

21Ć43

21Ć44

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Programming Guidelines

continued

Code Conventions A set of guidelines for writing code in uppercase or lowercase helps you to distinguish keywords from named objects. Category

Case Convention

Examples

SQL Commands

Uppercase

SELECT, INSERT

PL/SQL Keywords

Uppercase

DECLARE, BEGIN, IF

Datatypes

Uppercase

VARCHAR2, BOOLEAN

Identifiers and Parameters

Lowercase

v_sal, emp_cursor, g_sal

Database Tables and Columns

Lowercase

s_emp, order_date, id

Code Naming Conventions Develop a set of prefixes and suffixes to distinguish identifiers from other identifiers, from database objects, and from other named objects. Identifier

Naming Convention

Example

Variable

v_name

v_sal

Constant

c_name

c_company_name

Cursor

name_cursor

emp_cursor

Exception

e_name

e_too_many

Table Type

name_table_type

amount_table_type

Table

name_table

order_total_table

Record Type

name_record_type

emp_record_type

Record

name_record

customer_record

SQL*Plus substitution parameter

p_name

p_sal

SQL*Plus global variable

g_name

g_year_sal

Developing a Simple PL/SQL Block

21Ć45

21Ć46

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Programming Guidelines

continued

Indentation For clarity, indent each level of code. This enhances readability. ... BEGIN IF x=0 THEN y=1; END IF; ... END;

Developing a Simple PL/SQL Block

21Ć47

21Ć48

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary PL/SQL Blocks D

Declaration section: optional

D

Executable section: required

D

Exception handling section: optional

PL/SQL Identifiers D

Identifiers are defined in the declaration section.

D

Definition can be a scalar datatype with no internal components, such as NUMBER, VARCHAR2, DATE, and BOOLEAN.

D

Definition can be a composite datatype with internal components, such as TABLE and RECORD.

D

Definition can be based on the structure of another variable or a database object by using %TYPE and %ROWTYPE attributes.

D

Identifiers created with NOT NULL or CONSTANT options require initialization.

D

When referencing variables, keep in mind the scoping and conversion rules.

Conventions for Documenting, Writing, and Naming Code D

Document code with comments.

D

Develop conventions for writing text in uppercase and lowercase.

D

Develop conventions for naming identifiers.

D

Indent code to enhance readability.

Developing a Simple PL/SQL Block

21Ć49

21Ć50

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview This practice reinforces the basics of PL/SQL learned in this lesson, including datatypes, legal definitions of identifiers, and validation of expressions. You put all these elements together to create a simple PL/SQL block using Oracle Procedure Builder. Practice Contents D

Determining validity of declarations

D

Reviewing scoping and nesting rules

D

Developing a simple subprogram in Oracle Procedure Builder

Developing a Simple PL/SQL Block

21Ć51

21Ć52

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 21 1.

Evaluate each of the following declarations. Determine which of them are not legal and explain why. DECLARE v_id

NUMBER (4);

DECLARE v_x, v_y, v_z

VARCHAR2(10);

DECLARE v_birthdate

DATE NOT NULL;

DECLARE v_in_stock

BOOLEAN := 1;

DECLARE emp_record

emp_record_type;

a.

b.

c.

d.

e.

DECLARE TYPE name_table_type IS TABLE OF VARCHAR2(20) INDEX BY BINARY_INTEGER; dept_name_table name_table_type; f.

Developing a Simple PL/SQL Block

21Ć53

Practice 21 2.

continued

Suppose you embed a sub-block within a block, as depicted below. You declare two variables, V_CUSTOMER and V_CREDIT_RATING, within the main block. You also declare two variables,V_CUSTOMER and V_NAME in the sub-block. Determine the values for each variable in each case listed below. a.

The value of V_CUSTOMER in the sub-block is

b.

The value of V_NAME in the sub-block is

c.

The value of V_CREDIT_RATING in the sub-block is

d.

The value of V_CUSTOMER in the main block is

e.

The value of V_NAME in the main block is

f.

The value of V_CREDIT_RATING within the main block is

Scope Example DECLARE v_customer v_credit_rating

VARCHAR2(50) := ’Womansport’; VARCHAR2(10) := ’EXCELLENT’;

BEGIN DECLARE v_customer NUMBER (7) := v_name

SUBĆBLOCK 201; VARCHAR2(25):= ’Unisports’;

BEGIN v_customer

v_name

v_credit_rating

v_name

v_credit_rating

END; v_customer

END;

21Ć54

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 21 3.

continued

Create and execute a procedure named MULTIPLIER that accepts two numbers through variables. The first number should be divided by the second number and have the second number added to the result. The result should be written to a PL/SQL variable and printed to the screen.

If you have time, complete the following exercises. 4.

Build a function named ANN_COMP that computes the total compensation for one year. The annual salary and the annual bonus percentage will be passed to the function, and the bonus will need to be converted from a whole number to a decimal (for example, 15 to .15). If the salary is null, set it to zero before computing the total compensation. Likewise, if the bonus is null, set it to zero before computing the total compensation. Execute the function. Reminder: Use the NVL function to handle null values.

5.

Rewrite the MULTIPLIER procedure in Exercise 3 as a function named MULTI. Execute the function.

Developing a Simple PL/SQL Block

21Ć55

21Ć56

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

22 Interacting with Oracle

22Ć2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives In this lesson, you access the database and control transactions through SQL statements in PL/SQL. At the end of this lesson, you should be able to D

Use SELECT, INSERT, UPDATE, and DELETE commands in PL/SQL subprograms.

D

Determine the outcome of SQL statements by using implicit cursor attributes.

D

Control transactions within PL/SQL.

Interacting with Oracle

22Ć3

22Ć4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview When you need to extract information from or apply changes to the database, you must use SQL. PL/SQL supports full data manipulation language and transaction control commands within SQL. You can use SELECT statements to populate variables with values queried from a row in a table. Your DML commands can process multiple rows. Comparing SQL and PL/SQL Statement Types D

A PL/SQL block is not a transaction unit. Commits, savepoints, and rollbacks are independent of blocks, but you can issue these commands within a block.

D

PL/SQL does not support data definition language (DDL), such as CREATE TABLE, ALTER TABLE, or DROP TABLE.

D

PL/SQL does not support data control language (DCL), such as GRANT or REVOKE.

D

DBMS_SQL package allows you to issue DDL and DCL statements.

Interacting with Oracle

22Ć5

22Ć6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Retrieving Data Using PL/SQL Use the SELECT statement to retrieve data from the database. The SELECT statement contains an additional mandatory clause: the INTO clause. In the INTO clause, list the output variables for receiving the data. The SELECT statement must return exactly one row or an error will occur. Abridged Syntax SELECT INTO FROM WHERE

select_list variable_name | record_name table condition;

where: select_list

is a list of at least one column, and can include SQL expressions, row functions, or group functions.

variable_name

is the scalar variable to hold the retrieved value.

record_name

is the PL/SQL RECORD to hold the retrieved values.

table

specifies the database table name.

condition

is composed of column names, expressions, constants, and comparison operators, including PL/SQL variables and constants.

Take advantage of the full range of Oracle7 Server syntax for the SELECT statement. Guidelines D

Terminate each SQL statement with a semicolon (;).

D

Assign values into PL/SQL tables in a loop by declaring an explicit cursor.

D

The INTO clause is required for the SELECT statement when it is embedded within PL/SQL.

D

The WHERE clause is optional, and can be used to specify input variables, constants, literals, or PL/SQL expressions.

Interacting with Oracle

22Ć7

22Ć8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Retrieving Data Using PL/SQL

continued

Guidelines D

Specify the same number of output variables in the INTO clause as database columns in the SELECT clause. Be sure that they correspond positionally and that their datatypes are compatible.

D

Ensure that the datatype of the identifiers match the datatype of the columns by using the %TYPE attribute. The datatype and number of variables in the INTO clause match those in the SELECT list.

D

Terminate the PL/SQL block with the END statement. You can add the name of the subprogram after the keyword END for clarity.

D

Include at least one RETURN statement in a function.

D

Use group functions, such as SUM, in a SQL statement since group functions apply to groups of rows in a table.

Interacting with Oracle

22Ć9

22Ć10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Retrieving Data Using PL/SQL

continued

A PL/SQL RECORD can be used to easily create fields that match a database table’s columns. Each field has the same name and datatype as a column in the table. When retrieving all columns from a table, use a PL/SQL RECORD to hold the retrieved values.

Interacting with Oracle

22Ć11

22Ć12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Retrieving Data Using PL/SQL

continued

Avoid ambiguity in the WHERE clause by adhering to a naming convention that distinguishes database column names from PL/SQL variable names. Example Retrieve the order date and the ship date for the specified order. This example raises an unhandled runtime exception. PROCEDURE order_info (id s_ord.id%TYPE) IS date_ordered s_ord.date_ordered%TYPE; date_shipped s_ord.date_shipped%TYPE; BEGIN SELECT date_ordered, date_shipped INTO date_ordered, date_shipped FROM s_ord WHERE id = id; ... END order_info; PL/SQL> order_info (100); ERROR 0 at line 1, column 0 Unhandled exception ORA-01422: exact fetch returns more than requested number of rows ORA-06512: at line 7 PL/SQL checks whether an identifier is a column in the database; if not, it is assumed to be a PL/SQL identifier.

Interacting with Oracle

22Ć13

22Ć14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SELECT Exceptions SELECT statements within a PL/SQL block fall into the “Embedded SQL”ANSI classification. Be sure that the SELECT statement retrieves exactly one row; otherwise an exception is raised. An exception is an error that terminates a PL/SQL block. SELECT Exceptions Condition

Exception

The SELECT statement identifies more than one row.

TOO_MANY_ROWS exception (Oracle7 Server error number -1422).

The SELECT statement does not identify NO_DATA_FOUND exception (Oracle7 any rows. Server error number +1403). Note: Handle the raised exceptions with exception-handling routines, which will be covered in a later lesson. Alternatively, fetch multiple rows one-by-one in a loop by declaring an explicit cursor.

Interacting with Oracle

22Ć15

22Ć16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SELECT Exceptions

continued

TOO_MANY_ROWS Exception When more than one record is identified with a SELECT statement, Oracle7 Server raises an error number -1422, also referred to as TOO_MANY_ROWS, which is the predefined exception name. NO_DATA_FOUND Exception When no rows are identified with a SELECT statement, the NO_DATA_FOUND exception is raised, which is also Oracle7 Server error number +1403. In the “Processing Queries by Using Explicit Cursors” and “Error Handling” lessons, options for addressing these exceptions are addressed.

Interacting with Oracle

22Ć17

22Ć18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Manipulating Data Using PL/SQL Manipulate data in the database by using the DML commands. D

INSERT statement adds new rows of data to the table.

D

UPDATE statement modifies existing rows in the table.

D

DELETE statement removes unwanted rows from the table.

Inserting Data When adding rows to a table, you can eliminate unnecessary IN arguments. D

Use SQL function, such as USER and SYSDATE.

D

Generate primary key values by using database sequences.

D

Derive values in the PL/SQL block.

D

Add column default values.

Interacting with Oracle

22Ć19

22Ć20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Manipulating Data Using PL/SQL

continued

Updating and Deleting Data There may be ambiguity in the SET clause of the UPDATE statement because although the identifier on the left of the assignment operator is always a database column, the identifier on the right can be either a database column or a PL/SQL variable. Remember that the WHERE clause is used to determine which rows are affected. If no rows are modified, no error occurs, unlike the SELECT statement in PL/SQL.

Interacting with Oracle

22Ć21

22Ć22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SQL Cursor Whenever you issue a SQL command, the Server opens an area of memory in which the command is parsed and executed. This area is called a cursor. When the executable part of a block issues a SQL command, PL/SQL creates an implicit cursor, which has the SQL identifier. PL/SQL manages this cursor automatically. An explicit cursor is explicitly declared and named by the programmer. There are four attributes available in PL/SQL that can be applied to cursors. Note: More about explicit cursors will be covered in Lesson 24. SQL Cursor Attributes You can use these attributes in PL/SQL statements as you would functions, but not in SQL commands. They are useful to evaluate the result of a DML operation. PL/SQL does not consider a data manipulation language statement that affects no rows to have failed, unlike the SELECT statement, which returns an exception. Attribute

Description

SQL%ROWCOUNT

Number of rows affected by the most recent SQL statement (an integer value).

SQL%FOUND

Boolean attribute that evaluates to TRUE if the most recent SQL statement affects one or more rows.

SQL%NOTFOUND

Boolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows.

SQL%ISOPEN

Always evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are executed.

For more information, see PL/SQL User’s Guide and Reference, Release 2.3, Chapter 4, “Implicit Cursor Attributes” section.

Interacting with Oracle

22Ć23

22Ć24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SQL Cursor Attributes

continued

Example Write a procedure to delete rows that have the specified order number from the item table. Print the number of rows deleted to the screen. PROCEDURE del_rows (v_ord_id NUMBER) IS v_rows_deleted NUMBER; BEGIN DELETE FROM s_item WHERE ord_id = v_ord_id; v_rows_deleted := SQL%ROWCOUNT; TEXT_IO.PUT_LINE (TO_CHAR(v_rows_deleted) ||’ rows deleted.’); END del_rows;

Interacting with Oracle

22Ć25

22Ć26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Controlling Transactions Control the logic of transactions with COMMIT and ROLLBACK SQL commands, rendering some groups of database changes permanent, while discarding others. As with Oracle7, DML transactions start at the first command to follow a COMMIT or ROLLBACK, and end on the next successful COMMIT or ROLLBACK. These actions may occur within a PL/SQL block or as a result of events in the host environment (for example, ending a Procedure Builder session automatically commits the pending transaction). You can also include explicit locking commands (such as LOCK TABLE and SELECT ... FOR UPDATE) in a block. They take effect until the end of the transaction. COMMIT Command COMMIT ends the current transaction by making all pending changes to the database permanent. Syntax COMMIT [WORK]; where: WORK

is for compliance with ANSI standards.

ROLLBACK Command ROLLBACK ends the current transaction by discarding all pending changes. Syntax ROLLBACK [WORK]; where: WORK

is for compliance with ANSI standards.

Note: A transaction is defined as a sequence of SQL statements.

Interacting with Oracle

22Ć27

22Ć28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Controlling Transactions

continued

SAVEPOINT Command Alter the transactional logic with Oracle7 Server savepoints based upon runtime conditions. SAVEPOINT marks an intermediate point in the transaction processing. Syntax SAVEPOINT savepoint_name;

ROLLBACK TO SAVEPOINT discards pending changes made after the savepoint was marked. Syntax ROLLBACK [WORK] TO [SAVEPOINT] savepoint_name; where: savepoint_name

Interacting with Oracle

is a PL/SQL identifier.

22Ć29

22Ć30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary You can embed SQL within the PL/SQL block. You can use the following valid commands: Statement

Description

SELECT

Retrieves exactly one row into scalar variables or into a record variable.

INSERT

Adds a row.

UPDATE

Modifies one or more existing rows.

DELETE

Removes one or more existing rows.

COMMIT

Makes all pending transactions permanent.

ROLLBACK

Eliminates all pending transactions.

ROLLBACK TO SAVEPOINT

Eliminates all pending transactions since the named savepoint.

You can use SQL implicit cursor attributes to verify the outcome of these statements.

Interacting with Oracle

22Ć31

22Ć32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview In this practice, you create three procedures to input, update, and delete information in a table, all using DML statements within a PL/SQL block. Practice Contents D

Creating a procedure to insert data into a table

D

Creating a procedure to update data in a table

D

Creating a procedure to delete a record from a table

D

Verifying your changes to the table using Oracle Procedure Builder built-ins and implicit cursor attributes

Interacting with Oracle

22Ć33

22Ć34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 22 If you are not already connected to the database, be sure to connect now. 1.

2.

3.

Create a procedure to insert a new department into the S_DEPT table. a.

Use the S_DEPT_ID sequence generator for the department number.

b.

Create a parameter for the department name.

c.

Leave the region number null for now.

d.

Execute the procedure.

e.

Display the new department that you created.

Create a procedure to update the region number for an existing department. a.

Create a parameter for the department number.

b.

Create a parameter for the region name.

c.

Set the region number to the value that corresponds to the specified region name.

d.

Test the procedure. What happens if you enter a region name that does not exist?

e.

Display the department number, region number, and region name for the updated department.

Create a procedure to delete the department created in Exercise 1. a.

Create a parameter for the department number.

b.

Print to the screen the number of rows affected.

c.

Test the procedure. What happens if you enter a department number that does not exist?

What happens if you enter a department that has employees?

d.

Confirm that the department has been deleted.

Interacting with Oracle

22Ć35

Practice 22

continued

If you have time, complete the following exercise. 4.

Create a procedure named NEW_EMP to insert a new employee into the S_EMP table. a.

Create parameters for first name, last name, and job title.

b.

Use the S_EMP_ID sequence generator for the employee number.

c.

Compute the user ID by concatenating the first letter of the first name with the first seven letters of the last name, and converting all letters to lowercase.

d.

Set the start date to the current date.

e.

To determine the manager number, the department number, and the salary, first find the lowest-paid existing employee having the specified job title. Then, set these three values according to that existing employee. (If several people are tied for lowest-paid, choose any one of them.)

f.

Leave the comments and the commission percent empty.

g.

Verify the record has been added by viewing the employee’s number, userid, and salary.

22Ć36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

23 Controlling Flow in PL/SQL Blocks

23Ć2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives You can control the flow of your PL/SQL block by using conditional statements and loops. At the end of this lesson, you should be able to D

Conditionally control processing in a PL/SQL block.

D

Iterate statements by using various types of loops.

Controlling Flow in PL/SQL Blocks

23Ć3

23Ć4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview You can change the logical flow of statements within the PL/SQL block with a number of control structures. This lesson addresses two types of PL/SQL control structures: D

Conditional constructs with the IF statement

D

Looping constructs D

Basic loop to provide repetitive actions without overall conditions

D

FOR loops to provide for iterative control of actions based upon a count

D

WHILE loops to provide iterative control of actions based on a true statement

D

EXIT statement to terminate loops

For more information, see PL/SQL User’s Guide and Reference, Release 2.3, Chapter 3 “Control Structures.”

Controlling Flow in PL/SQL Blocks

23Ć5

23Ć6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The IF Statement The structure of the PL/SQL IF statement is similar to the structure of IF statements in other procedural languages. It allows PL/SQL to perform actions selectively based upon conditions. Syntax IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF; where: condition

is a Boolean variable or expression (TRUE, FALSE, or NULL).

Guidelines D

When writing code, remember the spelling of the keywords. D

ELSIF is one word.

D

END IF is two words.

D

If the controlling Boolean condition is TRUE, the associated sequence of statements is executed; if the controlling Boolean condition is FALSE or NULL, the associated sequence of statements is passed over.

D

Any number of ELSIF clauses are permitted.

D

There can be at most one ELSE clause.

D

Indent the conditionally executed statements for clarity.

Controlling Flow in PL/SQL Blocks

23Ć7

23Ć8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The IF Statement

continued

Simple IF Statements PL/SQL executes the conditional statements only if the condition is TRUE. If the condition is FALSE or NULL, then PL/SQL ignores the conditional statements. In either case, control resumes at the next statement in the program following END IF. Example Set the job title to Sales Representative and the region number to 35 if the last name is Dumas. . . . IF v_last_name = ’Dumas’ THEN v_job := ’Sales Representative’; v_region_id := 35; END IF; . . .

IFĆTHENĆELSE Statements If the condition is FALSE or NULL, you can use the ELSE clause to carry out other actions. As with the simple IF statement, control resumes in the program from the END IF. Example Set a flag for orders where there are fewer than five days between order date and ship date. . . . IF v_date_shipped - v_date_ordered < 5 THEN v_ship_flag := ’Acceptable’; ELSE v_ship_flag := ’Unacceptable’; END IF; . . .

Controlling Flow in PL/SQL Blocks

23Ć9

23Ć10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

The IF Statement

continued

Nested IF Statements Either set of actions of the result of the first IF statement can include further IF statements before specific actions are performed. Each nested IF statement must be terminated with a corresponding END IF. IFĆTHENĆELSIF Statements When possible, however, use the ELSIF clause instead of nesting IF statements. The code is easier to read and understand. The logic is clearly identified. If the action in the ELSE clause consists purely of another IF statement, it is more convenient to use the ELSIF clause. This makes the code clearer by removing the need for nested END IFs at the end of each further set of conditions and actions. Example For a given value entered, return a calculated value. If the entered value is over 100, then the calculated value is two times the entered value. If the entered value is between 50 and 100, then the calculated value is 50% of the starting value. If the entered value is less than 50, then the calculated value is 10% of the starting value. FUNCTION calc_val (v_start IN NUMBER) RETURN NUMBER IS BEGIN IF v_start > 100 THEN RETURN (2 * v_start); ELSIF v_start >= 50 THEN RETURN (.5 * v_start); ELSE RETURN (.1 * v_start); END IF; END calc_val;

Controlling Flow in PL/SQL Blocks

23Ć11

23Ć12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Building Logical Conditions Build a simple Boolean condition by combining number, character, or date expressions with a comparison operator. In general, handle null values with the IS NULL operator. Null Within Expressions and Comparisons D

Any expression containing a null value evaluates to NULL, with the exception of a concatenated expression, which treats the null value as the empty string.

D

Any simple comparison containing a null value evaluates to NULL.

D

An IS NULL comparison evaluates to TRUE or FALSE.

Boolean Conditions with Logical Operators Build a complex Boolean condition by combining simple Boolean conditions with the logical operators AND, OR, and NOT. In the accompanying logic tables, FALSE takes precedence for an AND condition and TRUE takes precedence in an OR condition.

Controlling Flow in PL/SQL Blocks

23Ć13

23Ć14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Building Logical Conditions

continued

The AND logic table can help you evaluate the possibilities for the Boolean condition you see below. . . . v_flag := v_reorder_flag AND v_available_flag; . . .

Controlling Flow in PL/SQL Blocks

23Ć15

23Ć16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Loop Statements PL/SQL provides a number of facilities to structure loops to repeat a statement or sequence of statements multiple times. Basic Loop The simplest loop consists of the body of statements to be repeated enclosed between the delimiters LOOP and END LOOP. Each time the flow of execution reaches the END LOOP statement, control is returned to the corresponding LOOP statement above it. This uncontrolled loop is an infinite loop that is to be avoided. To avoid an infinite loop, add an EXIT statement. The EXIT Statement You can terminate a loop using the EXIT statement. Control passes to the next statement after the END LOOP statement. You can issue EXIT either as an action within an IF statement, or as a standalone statement within the loop. In the latter case, you can attach a WHEN clause to allow conditional termination of the loop. Syntax LOOP statement1; statement2; . . . EXIT [WHEN condition]; END LOOP; where: condition

Controlling Flow in PL/SQL Blocks

is a Boolean variable or expression (TRUE, FALSE, or NULL).

23Ć17

23Ć18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Loop Statements

continued

Example Insert the first ten new line items for order number 101. . . . v_ord_id s_item.ord_id%TYPE := 101; v_counter NUMBER (2) := 1; BEGIN . . . LOOP INSERT INTO s_item (ord_id, item_id) VALUES (v_ord_id, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; . . .

Controlling Flow in PL/SQL Blocks

23Ć19

23Ć20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Loop Statements

continued

FOR Loop FOR loops have the same general structure as the loops you have already seen. In addition, they have a control statement at the front of the LOOP keyword to determine the number of iterations PL/SQL performs. Syntax FOR index IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP; where: index

is an implicitly declared integer whose value automatically increases or decreases by 1 on each iteration of the loop until the upper bound is reached.

REVERSE

causes the index to decrement with each iteration from the upper bound to the lower bound.

lower_bound

specifies the lower bound for the range of index values.

upper_bound

specifies the upper bound for the range of index values.

Note: Do not declare the index; it is declared implicitly as an integer.

Controlling Flow in PL/SQL Blocks

23Ć21

23Ć22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Loop Statements

continued

Example Print the number of times the loop is executed and the last value for the index based on the supplied lower bound and upper bound. PROCEDURE iterate (v_lower NUMBER, v_upper NUMBER) IS v_counter NUMBER(10) := 0; v_output NUMBER(10); BEGIN FOR i IN v_lower..v_upper LOOP v_counter := v_counter + 1; v_output := i; END LOOP; TEXT_IO.PUT_LINE(’Last value is ’||TO_CHAR(v_output) ||’. Total loops = ’||TO_CHAR(v_counter)); END iterate;

Guidelines D

Reference the index within the loop only; it is undefined outside the loop.

D

Reference the existing value of an index within an expression.

D

Do not reference the index as the target of an assignment.

Controlling Flow in PL/SQL Blocks

23Ć23

Condition is evaluated at the beginning of each iteration.

23Ć24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Loop Statements

continued

WHILE Loop You can use the WHILE loop to repeat a sequence of statements until the controlling condition is no longer TRUE. The condition is evaluated at the start of each iteration. The loop terminates when the condition is FALSE. If the condition is FALSE at the start of the loop, then no further iterations are performed. Syntax WHILE condition LOOP statement1; statement2; . . . END LOOP; where: condition

is a Boolean variable or expression (TRUE, FALSE, or NULL).

If the variables involved in the conditions do not change during the body of the loop, then the condition will remain TRUE, and the loop will not terminate.

Controlling Flow in PL/SQL Blocks

23Ć25

23Ć26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Loop Statements

continued

Nested Loops and Labels You can nest loops to multiple levels. You may nest FOR loops within WHILE loops, and WHILE loops within FOR loops. Normally, the termination of a nested loop does not terminate the enclosing loop (unless an exception was raised). However, you can label loops and exit the outer loop with the EXIT statement. Label names follow the same rules as other identifiers. A label is placed before a statement, either on the same line or a separate line. Label loops by placing the label before the word LOOP within label delimiters (<

Related Documents

Ocp Questions
May 2020 12
Adresse Postale Ocp
November 2019 12
Ocp - Sql&pl_sql(vol1)
November 2019 9
Ocp - Sql&pl_sql(vol3)
November 2019 1
Selftest Ocp 1z0-043
November 2019 12
Oracle 10g Ocp Topics
November 2019 5