304
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder Volume Three S Participant Guide Edition 1.1 M03991 T1001E11

OCP - SQL&PL_SQL(Vol3)

Embed Size (px)

Citation preview

Page 1: OCP - SQL&PL_SQL(Vol3)

���������� �� ��� �� ������ ������ ���� ���������� ����� ��� ����� � �������� ����

������� ���

����

�����

Page 2: OCP - SQL&PL_SQL(Vol3)

Authors

Neena KochharDebby Kramer

Technical Contributorsand Reviewers

Christian BauwensDebra BowmanLenny BrunsonJackie CollinsRalf DurbenBrian FryAnthony HolbrookKarlene JensenSarah JonesGlenn MaslenSundar NagarathnamSandra SchrickUlrike SchwinnRosemarie TrumanJenny TsaiLaura Van Deusen

Publishers

Stephanie JonesKimberly LeeJennifer RobertsonMark Turangan

��������� �������� ������������ ����� ����� ��� ������ ���������

��� ��� !�������� �������� ����������� ��"��!����� �" ������ �����������# �� ��

�������� ���� � ������� �����!��� ���������� ������������ �� �� ��� ������$

� �� ��� �� ���� ��������� %� ��������� ��&� '������ ����������� �" ��� ��"�&���

�� �����%����� (" ���� ��� !�������� �� ��������� �� � )�*� +�����!��� ������ �"

��� ,�����!��� �" ,�"����� ���� �� �� ��������� &��� '��������� '����� ��� ��� "��$

��&��� ������ �� �������%��-

������� ���� ������

)��� � ��������� �� ������� �� %� ��� +�����!��� �� � %.��� �� ������������ "��

��!!������ ��!� ��� ��"�&��� ��� ����� %� ���!�� �� %� '��������� '����� ��"�$

&��� ���� /������ ��&� ��� �� ��� "���� �� � %��������� 0�1 0�1 0��1 �" ,/�'*

�2����3$3��� '����� �� �������� ,��� ��� ��!� ��� *�"�&��� 0����%�� ��441�

��� !������� �� ��� ������� �" �� !�� ��� %� ������ �� ��� "��! �� %� ��� !����

&���� � ��� �5����� ����� &������ ���!������ �" ���6����&��� �� ������ *�������

��� � �"������ ������������ ��� ����� ������� �� � ��������� �" ��������� ��& ���

!�� ��� �� �� ����� ���7�� ���!���� ����������

(" ���� ��� !�������� �� ��������� �� �)�*� +�����!��� ������ ��� &����� ��� ,�$

����!��� �" ,�"����� ���� �� �� ��������� &��� 8'��������� '������9 �� ��"���� ��

/�' 2����3$�:� '����� �� ,���$+������� ���� ���� ��������� ((( 0; �� ��431�

�� ��"��!����� �� ���� ��� !��� �� � %.��� �� ������ &���� � ������� (" �� "���

��� ���%��!� �� ��� ��� !��������� ������ ������ ���! �� &������ �� 6����&���

�� ������ *�������� ������ ������������ 2 ������ <��=&��� >�5 �2�4�� '��$

&���*������ ���:�2������������������ ���� ���&������ ���� ���� ��� !���

�� ����� "����

*?@A<� �� <@7*?@� <����� �� > ������ ,��������7�� ������3 *������ ������

*������ ,���������7�� ��� ,�������7� ��� �����!��=� �� ���������� �����$

!��=� �" ������ ������������

��� ����� ���� ��� �� ��!���� ��!�� ��� ��� "�� ������"������� � ������ �����

��� !�� %� �����!��=� �" ����� ���������� �&�����

Page 3: OCP - SQL&PL_SQL(Vol3)

�������� �� ��

��

Page 4: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� �����������

Page 5: OCP - SQL&PL_SQL(Vol3)

�������� �� �� ����

� !�������

This lesson provides an overview of how to create and use PL/SQL programunits and subprograms using Oracle Procedure Builder.

At the end of this lesson, you should be able to

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

� Describe basic PL/SQL program constructs.

� Describe the Oracle Procedure Builder tool.

Page 6: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� ����������"

Page 7: OCP - SQL&PL_SQL(Vol3)

�������� �� �� ���#

��������

$%�� �� �� &

PL/SQL (Procedural Language/SQL) is an extension to SQL, incorporating many ofthe design features of programming languages of recent years. It allows the datamanipulation and query statements of SQL to be included within block-structured andprocedural units of code, making PL/SQL a powerful transaction processinglanguage.

�������� ���' ��

You can take advantage of the procedural capabilities of PL/SQL, which areunavailable in SQL.

Modularize Program Development

� Group logically related statements within blocks.

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

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

Declare Identifiers

� Declare variables, constants, cursors, and exceptions, and then use them in SQLand procedural statements.

� Declare variables belonging to simple and composite datatypes.

� Declare variables dynamically based upon the data structure of tables andcolumns in the database.

Program with Procedural Language Control Structures

� Execute a sequence of statements conditionally.

� Execute a sequence of statements iteratively in a loop.

� Process individually the rows returned by a multiple-row query with an explicitcursor.

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

Handle Errors

� Process Oracle7 Server errors with exception handling routines.

� Declare user-defined error conditions and process them with exception handlingroutines.

Continued

Page 8: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� ����������(

Page 9: OCP - SQL&PL_SQL(Vol3)

�������� �� �� ���)

�������� ���������

�������� �� �� *���������

Portability

� Since PL/SQL is native to Oracle, you can move programs to any hostenvironment that supports Oracle and PL/SQL.

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

Integration

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

� Variables and datatypes in PL/SQL and SQL are compatible. Therefore, PL/SQLbridges the gap between convenient access to database technology and the needfor procedural programming capabilities.

Improve Performance

� PL/SQL can improve the performance of an application. The benefits differdepending upon the execution environment.

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

Page 10: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� �����������

Page 11: OCP - SQL&PL_SQL(Vol3)

�������� �� �� ���+

�� ����, ���������

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

Section Description Inclusion

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

Optional

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

Mandatory

Exception Handling Specifies the actions to perform whenerrors and abnormal conditions arisewithin 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 bysemicolons. However, END and all other PL/SQL statements do require a semicolonto terminate the statement. You can string statements together on the same line.However, this method is not recommended for clarity or editing.

Page 12: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� �����������-

Page 13: OCP - SQL&PL_SQL(Vol3)

�������� �� �� �����

�� ����, ��������� ���������

Every unit of PL/SQL comprises one or more blocks. These blocks can be entirelyseparate or nested one within another. Therefore, one block can represent a small partof another block, which in turn can be part of the whole unit of code.

�� �����' .���������

The following list outlines a variety of different PL/SQL program constructs usingthe basic PL/SQL block. They are available based on the environment where they areexecuted.

ProgramConstruct Description Availability

Anonymous Block Unnamed PL/SQL block that isembedded within an application oris issued interactively.

All PL/SQLenvironments.

Stored Procedure orFunction

Named PL/SQL block that canaccept parameters and can beinvoked repeatedly.

Oracle7 Server withProcedural Extension.

ApplicationProcedure orFunction

Named PL/SQL block that canaccept parameters and can beinvoked repeatedly.

Components ofDeveloper/2000, forexample Forms.

Package Named PL/SQL module thatgroups together related procedures,functions, and identifiers.

Oracle7 Server withProcedural Extension.

Database Trigger PL/SQL block that is associatedwith a database table and is firedautomatically.

Oracle7 Server withProcedural Extension.

Application Trigger PL/SQL block that is associatedwith an application event and isfired automatically.

Components ofDeveloper/2000, forexample Forms.

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

Page 14: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� ������������

Page 15: OCP - SQL&PL_SQL(Vol3)

�������� �� �� �����

�� ����, ��������� ���������

The two types of constructs covered in this course are anonymous blocks andsubprograms.

/���0'��� ����,�

Anonymous blocks are unnamed blocks. They are declared at the point in anapplication where they are to be executed and are passed to the PL/SQL engine forexecution at runtime. You can embed an anonymous block within a precompilerprogram and within SQL*Plus or Server Manager. Triggers in Developer/2000components consist of such blocks.

�� 1�����'�

Subprograms are named PL/SQL blocks. You can declare them either as proceduresor as functions. Procedures perform actions, and functions return values.

Developer/2000 components allow you to declare procedures and functions as part ofthe application (a form or report), and call them from other procedures, functions, andtriggers.

Page 16: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� �����������"

Page 17: OCP - SQL&PL_SQL(Vol3)

�������� �� �� ����#

2%� �� 3������'���

PL/SQL is not an Oracle product in its own right; it is a technology employed by theOracle7 Server and by certain Oracle tools. Blocks of PL/SQL are passed to andprocessed by a PL/SQL engine, which may reside within the tool or within theOracle7 Server. The engine used depends on where the PL/SQL is being invoked.

�� 3����� �� �%� ������) ������

When you submit blocks from a Pro* program, user-exit, SQL*Plus, or ServerManager, the PL/SQL engine in the Oracle7 Server processes them. It breaks the SQLwithin the block into separate statements and sends them to the SQL StatementExecutor. This means that a single transfer is required to send the block from theapplication to the Oracle7 Server, thus improving performance especially in aclient-server network. Stored subprograms can be referenced by any number ofapplications connected to the database.

�� �� ������ 2����

Many Oracle tools, including Developer/2000, have their own PL/SQL engine, whichis independent of the engine present in the Oracle7 Server.

The engine filters out SQL statements and sends them individually to the SQLStatement Executor in the Oracle7 Server. It processes the remaining proceduralstatements in the Procedural Statement Executor, which is within the PL/SQL engine.

The Procedural Statement Executor processes data that is local to the application (thatis already inside the client environment, rather than the database). This reduces worksent to the Oracle7 Server and the number of memory cursors required.

Note: Procedures and functions declared as part of a Developer/2000 application aredistinct from those stored in the database, although their general structure isthe same. Stored subprograms are database objects and are stored in the DataDictionary. They can be accessed by any number of applications.

Application subprograms pass blocks to that application’s local PL/SQLengine. Work is done at the application site, not at the server site.

Page 18: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� �����������(

Page 19: OCP - SQL&PL_SQL(Vol3)

�������� �� �� ����)

/ ��� �������� �������

Oracle Procedure Builder is a tool you can use to create, execute, and debug PL/SQLprograms used in your application tools, such as a form or a report, or on the Oracle7Server through its graphical interface.

���������� �� 4�����1'��� 3������'���

Procedure Builder’s development environment contains a built-in editor for you tocreate or edit subprograms. You can compile, test, and debug your code.

������� .������������ �� 4�����1'���

Application partitioning through Procedure Builder is available to assist you withdistribution of logic between client and server. Users can drag and drop a PL/SQLprogram unit between the client and the server.

Page 20: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� � ��� �� ����� �������� ������������

Page 21: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� �

��

Page 22: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����

��������

Page 23: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���

��������

A key feature of procedural programming is the ability to create and debug codequickly and easily. Procedure Builder provides all of the functionality necessaryfor you to successfully develop and debug PL/SQL programs. This lessonenables you to manipulate PL/SQL code using Procedure Builder.

At the end of this lesson, you should be able to

� Identify the advantages of developing and debugging PL/SQL programs inProcedure Builder.

� Manage program units by using the Object Navigator.

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

� Define and compile procedures by using the Program Unit editor.

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

� Set a breakpoint to suspend program execution.

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

� Test possible solutions by changing variables and procedures at runtime.

Page 24: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����!

Page 25: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���"

����#

Procedure Builder is an integrated development environment. It provides for theediting, 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 clientand server. You can improve your application development efforts by using thefeatures available in Procedure Builder. You will become familiar with these featuresby learning about each component’s function. Once you are familiar with theProcedure Builder environment, you will cover the PL/SQL syntax.

����� ��� � $����

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 UnitEditor

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

Database Trigger Editor Create and edit database triggers.

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

Page 26: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����%

������ ����&&��� '�(��� ����

Page 27: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���)

��� ����� ��� � '�(��� ����

Procedure Builder is an integrated, interactive environment that you can use to create,execute, and debug PL/SQL programs. Using Procedure Builder, you can buildportable database programs quickly and easily.

������� ������ *� �(&�� +�����&��

� Create and edit subprograms.

� Compile subprograms to perform syntactical error checking.

� Test subprograms.

� Debug subprograms.

������ ' ������ ������ *� �(&��

� Create database triggers.

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

� Build and edit client-side libraries.

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

Page 28: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����,

����� ��� � '�&(�����

����� ��� � '�&(�����

Page 29: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ����

����� ��� � '�&(�����

-. ����� /�������

The Object Navigator provides an outline style interface to browse objects, view therelationships between them, and edit their properties.

-. ���(�

The Interpreter is the central debugging workspace of Procedure Builder. It is atwo-pane window where you display, debug, and run PL/SQL program units. It alsointeractively supports the evaluation of PL/SQL constructs, SQL commands, andProcedure Builder commands.

-. ����& ���� +����

The easiest and most common place to enter PL/SQL source code is in the ProgramUnit editor. You can use it to edit, compile, and browse warning and error messagesduring application development.

-. ���� ����& ���� +����

The Stored Program Unit editor is a GUI environment for editing server-sidepackages and subprograms. The compile operation submits the source text to theserver-side PL/SQL compiler. To debug server-side program units you can drag acopy of the program unit to the client side using the Object Navigator.

-. *������ -��� +����

The Database Trigger editor is a GUI environment for editing database triggers. Thecompile operation submits the source text to the server-side PL/SQL compiler.

�� �� 0 (

Oracle Procedure Builder has a help facility that provides assistance at any timeduring your session. You can access it from the menu bar.

Page 30: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����1

����� �. ����2 -��

Page 31: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � �����

����� ��� � '�&(����� ���������

����� �. ����2 -��

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 withProcedure Builder. You can invoke the Quick Tour by choosing the Quick Tour menuitem from the Help menu.

Procedure Builder Basics

Become familiar with the Object Navigator to create and manage your PL/SQLobjects. 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/SQLprogram 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. Itdescribes how to set breakpoints, step through your code, and peruse the Stack nodeto change the value of the variable.

Organizing PL/SQL

Step through application partitioning between the client and server, including usinglibraries and moving subprograms between the client and server.

Procedure Builder Features

Review the kinds of application-building tasks you can perform using ProcedureBuilder.

Page 32: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ������

����� '� '���

Page 33: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ����

����� ��� � '�&(����� ���������

����� '� '���

Developer/2000 provides further help in the form of Cue Cards. Their purpose is toprovide just-in-time coaching for frequently performed tasks. You can invoke CueCards 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 tocomplete a task, while concept cards describe a particular concept with staticgraphics. When invoked, Cue Cards display a list of topics that are divided into twocategories:

� Task: What would you like to do?

� Concept: Learn About

To display the cue card for any of these topics, click the appropriate button to the leftof the item.

Cue Cards include a set of six buttons that you use to navigate to the information yourequire.

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.

Page 34: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����!

!

-. ����� /�������

"�

!

!"

��������� �� ��� ���� ��������� ��������� ��� ����

������ ����! ��� ��� "

Page 35: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ����"

-. ����� /�������

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

����� /������� '�&(�����

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

Type icon Indicates the object type.

Object name Indicates the name of the object.

Find field Used to search for a named object.

Page 36: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����%

-. ����� /������� 3���� ������ ��

!

��������� ������������� �������� ���

������� �������� � ��� ��� �

!

Page 37: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ����)

-. ����� /������� ���������

-. ����� /������� 3���� ������ ��

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

+ &��� �� �. 3���� ������ ��

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 anobject 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. Notethat objects must be copied to a valid location in the objecthierarchy.

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

Collapse Collapses the first level of subobjects of the currently selectedobject.

Expand All Expands all levels of subobjects of the currently selected object.

Collapse All Collapses all levels of subobjects of the currently selected object.

Page 38: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����,

������ �� �. /�������

Page 39: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � �����

-. ����� /������� ���������

����� /������� ������

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

Object Node Description

Program Units PL/SQL construct that can be independently recognized andprocessed by the PL/SQL compiler.

Program Units –Specification

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

Program Units –References

Procedures, functions, anonymous blocks, and tables that theprogram unit references.

Program Units –Referenced By

Procedures, functions, anonymous blocks, and tables thatreference the program unit.

Libraries Collection of PL/SQL packages, procedures, and functionsstored 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 debuggingprogram units.

Debug Actions Actions that enable you to monitor or interrupt the executionof PL/SQL program units.

Stack Chain of subprogram calls, from the initial entry point downto the currently executing subprogram.

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

Page 40: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����1

Page 41: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � �����

-. ����� /������� ���������

4������� ������ ����� �. ����� /�������

Use the Vertical Button Bar and the Find Field on the Object Navigator to managePL/SQL constructs, debug actions, and database objects.

'����� � ����5

1. Select the Libraries object.

2. Click the Create button.

The new library subobject will appear with a default name.

������ � ����5

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 theDatabase radio button. Click the OK button to accept the options.

+6(������ � /��

1. Select a valid node.

2. Click the Expand button or the Expand All button.

���.��� �� �� �����

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 ObjectNavigator is highlighted.

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

Page 42: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ������

-. ���(�

Page 43: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ����

-. ���(�

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

���(� '�&(�����

Component Description

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

Close button Closes the Interpreter.

Source pane Displays a read-only copy of the program unitcurrently selected.

Interpreter pane Provides a command line interface to PL/SQL andProcedure Builder.

Scroll bar Scrolls the window.

Split bar Changes the relative amount of space occupied by eachpane in the Interpreter.

+6������ � ������ �����

From the PL/SQL prompt in the Interpreter pane, enter the name of the procedure.Terminate the command with a semicolon.

�5���6

procedure_name [(argument1[, argument2, ...])];

Page 44: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����!

-. ���(� ���

������� �� !! ����������"

� ������ �� ������� ����������� �������"

� ������� � �� ������������"

Page 45: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ����"

-. ���(� ���������

-. ���(� ���

Using the Interpreter pane, you can interactively evaluate PL/SQL constructs andSQL commands.

+6������ ��� **� ����&���

From the PL/SQL prompt in the Interpreter pane, enter SQL data definition languagestatements. To create the B_TEST table, enter the following statement:

PL/SQL> CREATE TABLE b_test (col1 NUMBER);

���&��� '�&(� ����� �� ������

From the PL/SQL prompt in the Interpreter pane, enter PL/SQL statements. Forexample, 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.

+6������ ��� ����&���

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 followingstatement:

PL/SQL> SELECT * FROM b_test;

Page 46: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����%

-. ����& ���� +����

!

���� � �� ���������� ������������������

� ���� �� ��� ���� ������ ���� ���

���� ����� #���������

!

Page 47: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ����)

-. ����& ���� +����

Create, edit, and compile PL/SQL source code by using the Program Unit editor.

4�.��� �� *��( �5 �. ����& ���� +����

� Choose Program Unit Editor from the Tools menu.

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

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

����& ���� +���� '�&(�����

Component Description

Compile button Compiles the program unit appearing in the SourceText pane.

Apply button Saves any changes made to the program unit in theeditor since it was first opened or since the last applyor revert operation.

Revert button Restores the state of the program unit to the last applyor 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 programunit. You can use the drop down list to select anotherprogram unit to edit.

Source Text pane Allows you to enter and edit PL/SQL program unitsource text.

Compilation Messagepane

Displays error messages generated as a result ofcompilation.

Page 48: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� �����,

'����� � ����& ����

������ �$� %������ &���"� '���� �$� ���"�

Page 49: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � �����

-. ����& ���� +���� ���������

'����� � ����& ����

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

/��������� '�&(� ����� +��

1. Click the Compile button in the Program Unit editor.

Error messages generated during compilation are displayed in the CompilationMessage pane.

2. Click an error message.

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

+6(����� � ����& ���� �� � -6� $�

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. Clickthe OK button to accept these entries.

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

Page 50: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ���� 1

-. ���� ����& ����

� !

����� �� ��� ���� ������ ���� ���� ���� ����� #���������

���� �� ��� ���!

Page 51: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ��� �

-. ���� ����& ���� +����

Create, edit, and compile server-side program units by using the Stored Program Uniteditor. Visually and functionally, creating Stored Program Units in Procedure Builderis very similar to creating client-side Program Units.

'�������� �� �. ��� ) ��

When initially invoked, Procedure Builder is a standalone session. To connect to adatabase, select Connect from the File menu, and enter the appropriate username,password, and database connection string.

4�.��� �� *��( �5 �. ���� ����& ���� +����

� Choose Stored Program Unit Editor from the Tools menu.

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

���� ����& ���� +���� '�&(�����

Component Description

Owner drop down list Displays usernames whose stored program unitsyou can access.

Source Text pane Allows you to enter and edit PL/SQL storedprogram unit source text.

Compilation Message pane Displays error messages generated as a result ofcompilation.

Name drop down list Displays a list of the owner’s stored programunits.

Save button Compiles and saves the program unit to theOracle7 Server.

Page 52: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ���� �

*������� � ���� ����& ����

Page 53: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���

*������� � ���� ����& ����

Sometimes developers may not want to (or not have the privilege to) debug or refinea stored program unit in place on the server. In such cases, you may choose to drag acopy of the program unit to the client side.

*������� � ���� ����& ����

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 nodeand release the mouse button.

The selected program unit appears as a Stored Program Units subobject.

Page 54: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ���� !

������� '�� �� �. ���� ���

������ ���� ��������� ���� (��������� ���

Page 55: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ��� "

���&��� *��� 7������ �� �. ���(�

You can use the Object Navigator to examine and modify parameters in aninterrupted program. By invoking the Object Navigator within the Interpreter, youcan perform debugging actions entirely within the Interpreter window. Alternatively,you can interact with the Object Navigator and Interpreter windows separately.

����2��� �. ����� /������� ���

1. Select PL/SQL Interpreter from the Tools menu to open the Interpreter if it is notalready 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.

������� ���� -6� �� �. ���� ���

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.

Page 56: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ���� %

������ � ��2(����

)���*����� !���� �������

Page 57: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ��� )

������ � ��2(����

If you encounter errors while compiling or running your application, you should testthe code and determine the cause of the error. To effectively determine the cause ofthe error, you step through the code, line by line. Eventually, you identify the exactline of code causing the error. One method to assist you is a breakpoint, which haltsexecution at any given point and permits you to examine the status of the code on aline-by-line basis.

������ � ��2(����

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 theInterpreter 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/SQLprompt.

4�������� *��� 7������

Debug actions, like breakpoints, can be viewed in the Object Navigator under theheading Debug Actions. Double-click the Debug Actions icon to view a descriptionof the breakpoint. Remove breakpoints by double-clicking the breakpoint linenumber.

Page 58: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ���� ,

*��� '�&&����

�������� �����������

Page 59: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ��� �

������ � ��2(���� ���������

��((��� -.���. '��

When a breakpoint is reached, you can use a set of commands to step through thecode. You can execute these commands by clicking the command buttons on theInterpreter toolbar or by entering the command at the Interpreter prompt.

'�&&���� �� ��( -.���. '��

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 thesubsequent 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 interruptedagain due to a debug action.

Reset Aborts execution at the current debug levels.

Page 60: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����!1

��((��� -.���. '��

������ �������� )���*����� !���� �������

Page 61: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���!�

������ � ��2(���� ���������

*�&����� �. '��� �� +�

Once the breakpoint is found at runtime, you can begin stepping through the code. Anarrow (=>) 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. Atthat time, PL/SQL displays an error message.

Page 62: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����!�

'.������ � 3� �

!

� ��* �$� ����* ���� � ��* �$� ������ � �� ��� ����� �$� ��� �� ��

� ��* �$� +� ������!

Page 63: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���!

+6�&����� ���� 3���� �

Using Procedure Builder, you can examine and modify local variables andparameters in an interrupted program. The Stack node in the Navigator pane is whereyou can view and change the values of local variables and parameters associated withthe current program unit located in the Call Stack. When debugging code, check forthe absence of values as well as incorrect values.

+6�&����� 3� �� ��� -����� �. ������ �� �����

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 variableediting, 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 theInterpreter PL/SQL prompt.

Page 64: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����!!

��&&�5

Page 65: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���!"

��&&�5

There are clear advantages to developing and debugging PL/SQL programs inProcedure Builder:

7(( ������� �����������

� Manage program units using the Object Navigator.

� Move program units between client and server.

+�����

� Create and compile procedures by using the Program Unit editor.

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

+6������ +�����&��

� Execute program units by using the PL/SQL Interpreter.

*�������

� Suspend program execution by using breakpoints.

� Step through code to determine the location of the error.

� Examine local variables to determine the cause of the error.

� Modify variable values to test possible solutions at runtime.

Page 66: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����!%

������ ����#

Page 67: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���!)

������ ����#

This practice will familiarize you with the Procedure Builder environment andwindows.

������ '������

� Exploring Procedure Builder menus and windows

� Creating a program unit

� Executing a program unit

Page 68: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����!,

Page 69: OCP - SQL&PL_SQL(Vol3)

������ �� ����� ��� � ���!�

������ ��

1. Load and execute a loop counter.

a. Launch Procedure Builder. Your instructor will give you the logininformation.

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

c. Execute the procedure from the Interpreter pane. Pass a numeric value into theprocedure 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 ISBEGIN 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;

Page 70: OCP - SQL&PL_SQL(Vol3)

����������� �� ��� � ��� ��� ������ ����� ����� ��� ����"1

Page 71: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ����

��������� �

��

Page 72: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!�

Page 73: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!"

��#����$��

Modularity allows you to break your code into manageable, well-defined logicalunits. 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. Thislesson covers the structure of subprograms and how to invoke them.

At the end of this lesson, you should be able to

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

� Explain the differences between and benefits of procedures and functions.

� Develop subprograms.

� Invoke subprograms from Procedure Builder.

Page 74: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!%

Page 75: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!&

�$��$���

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

� Procedures to perform actions

� Functions to compute a value

� Packages to bundle logically related procedures and functions

������ �� '��������� ��������� (

These program units can be created in a variety of environments, includingserver-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 orapplication.

From only the application inwhich it was created.

Availability By way of database security. Independently of, and inaddition to, stored subprograms.

Subprograms are composed of a number of sections:

� A header to name and type the block

� An optional declarative section to set up local identifiers

� An executable part to perform the actions

� An optional exception handling section to handle exceptions

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

Page 76: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!)

Page 77: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!*

+������ � ���������

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 theDatabase 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 usingSQL*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 theCompile button. If using SQL*Plus, start your file at the SQL prompt.

4. Invoke the successfully compiled procedure or function.

,��������

� SQL*Plus is another development environment for writing and for initial testingof a procedure, although you will need to test the procedure by invoking it froman application.

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

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

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

Page 78: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!-

Page 79: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!.

+������ � ���������

Create a PL/SQL procedure to store a series of actions for later execution. Theprocedure can contain zero or more parameters, which are arguments that you listwhen calling the procedure.

�/��0

PROCEDURE name[(parameter,...)]

ISpl/sql_block;

where: name is the procedure name, which adheres to thestandard Oracle naming rules.

parameter is the parameter syntax shown below.

pl/sql_block is the procedural body that defines the actionperformed by the procedure.

The parameter syntax is as follows.

�/��0

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

expr is the value to initialize the parameter.

,��������

� Start the PL/SQL block with the keyword IS.

� Enter any local declarations between IS and BEGIN.

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

Page 80: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!1�

Page 81: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!11

+������ � ��������� ���������

���������� ���� �����

Transfer values to and from the calling environment through parameters. There aretwo types that you use. When declaring a procedure, the formal parameter is used todefine the values used in the executable portion of the PL/SQL block. The actualparameter, or argument, is referenced when invoking a subprogram.

���� ���� ����� 2�� 3�� �� ���� �����

Parameter Mode Description

IN Default argument.

Passes a value from the calling environment into thesubprogram.

Formal parameter acts as a constant—you cannotoverwrite the value.

Actual parameter can be an expression, a constant, aliteral, or an initialized variable.

OUT Must be specified.

Returns a value from the procedure to the callingenvironment.

Formal parameter acts as an uninitialized variable.

Formal parameter cannot be assigned to anothervariable or to itself.

Actual parameter must be a variable; it cannot be aconstant or expression.

IN OUT Must be specified.

Passes a value from the calling environment into theprocedure, and returns a possibly different value fromthe procedure to the calling environment.

Formal parameter acts as an initialized variable.

Formal parameter can be used as a normal variable; itcan be assigned to a value.

Actual parameter must be a variable.

Page 82: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!1�

Page 83: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!1"

+������ � ��������� ���������

40� ���

Update the salary of the specified employee to the specified amount through aprocedure.

PROCEDURE change_salary(v_emp_id IN NUMBER, -- formal parameters v_new_salary IN NUMBER)

ISBEGIN -- begin PL/SQL block

UPDATE s_empSET salary = v_new_salaryWHERE id = v_emp_id;

COMMIT;END change_salary;

This procedure, when invoked, will take the parameters for the employee number andthe 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 SimplePL/SQL Block.”

4�� ���� ��������/ �5 '��� ���

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

� Generate the primary key using a database sequence.

� Record the username from the USER function.

� Record the current date from the SYSDATE function.

� Take advantage of business rules to compute input values automatically using aformula.

Page 84: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!1%

Page 85: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!1&

+� ����� 3������ �� ����������

A procedure can contain a list of parameters, but does not have to return a value. It isinvoked in place of a complete PL/SQL statement. A function differs from aprocedure in two ways:

� You invoke the function as part of an expression.

� A function must return a value.

��� 3������

There are both user-defined functions, covered in this lesson, and SQL functions. Youare already familiar with SQL functions. You call the function with actual parametersfrom within a SQL command, such as SELECT.

-- Example Number FunctionsROUND (1896,2)TRUNC (1892,-2)

-- Example Group FunctionsSUM (s_emp.salary)AVG (s_ord.total)

-- Other System FunctionsUSER -- usernameSYSDATE -- current date and times_dept_id.NEXTVAL -- database sequence value

A procedure containing one OUT argument can be rewritten as a function containinga RETURN statement.

Page 86: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!1)

Page 87: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!1*

+������ � 3�����

Create a PL/SQL function to return a value to the calling environment. You mustdeclare the RETURN datatype in the header section of the function definition, anddefine the value to be returned in the PL/SQL block. You can also declare a list ofparameters to be passed into the function.

�/��0

FUNCTION name[(parameter,...)]RETURN datatype

ISpl/sql_block;

where: name is the function name, which adheres to thestandard 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 actionperformed by the procedure.

6�� 746�75 ����� ��

Remember to include a RETURN statement in the PL/SQL block. The function mustset the value of the return parameter and be of the same datatype specified in theRETURN clause of the function definition. Multiple RETURN statements areallowed, but only one will be executed by any one call. Typically, the multipleRETURN statements are within an IF statement.

When creating the function from Procedure Builder, the CREATE OR REPLACEportion of the syntax is implied. Therefore, when creating the function fromSQL*Plus, begin the statement with CREATE OR REPLACE.

Page 88: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!1-

Page 89: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!1.

+������ � 3����� ���������

40� ���

Return the tax based on the value parameter in a function.

FUNCTION tax(v_value IN NUMBER)RETURN NUMBER

ISBEGIN

RETURN (v_value * .07);END tax;

Avoid using the OUT and IN OUT modes with functions. Functions are designed toreturn a single value.

Page 90: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!��

Page 91: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!�1

�$�8�� ��������� �

You can call procedures and functions from any tool or language that supportsPL/SQL. From PL/SQL, you can call a procedure with a direct call, and call afunction as part of an expression.

�$�8�� ���������� 2�� ��������� ������

Enter the procedure name with any actual parameters, if applicable, at the ProcedureBuilder Interpreter prompt. Procedure Builder then performs the action specified inthe procedure.

40� ���

Use the CHANGE_SALARY procedure to change the salary to 1000 for employeenumber 17.

PL/SQL> change_salary (17, 1000);

Note: You may want to confirm the changes by issuing a SELECT statement.

�$�8�� ���������� 2�� '����� ���������

The example on the facing page illustrates how you can invoke a procedure fromanother procedure. In the example, procedure CHANGE_SALARY is being invokedfrom procedure PROCESS_SAL. Similarly, you can invoke a function from a storedprocedure or a PL/SQL anonymous block.

To invoke procedures from SQL*Plus, use the EXECUTE command. Use SQL*Plusbind variables to hold returned values. You can also use SQL*Plus substitutionvariables through the ampersand (&) and variable name.

Page 92: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!��

Page 93: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!�"

�$�8�� ��������� � ���������

�$�8�� �������� 3������

You can invoke a standalone function created in Procedure Builder. First, you mustcreate a variable called the “identifier” to hold the returned value.

�/��0

CREATE variable

where: variable is one of the following:

NUMBER var_name Specifies a variable, var_name, of the datatype[PRECISION number] NUMBER. PRECISION determines the [SCALE number] maximum number of objects. SCALE

determines where rounding should occur.

DATE var_name Specifies a variable, var_name, of the datatypeDATE.

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

After creating the variable, you execute the function. Finally, you view the variablevalue.

40� ���

Display the tax based on a value. Use the TAX function created earlier.

PL/SQL> .CREATE NUMBER x PRECISION 4PL/SQL> :x := tax(100);PL/SQL> TEXT_IO.PUT_LINE (TO_CHAR(:x));

7

For more information, seeProcedure Builder Developer’s Guide, “Working with PL/SQL Constructs.”

Note: To invoke functions from SQL*Plus, use the EXECUTE command. UseSQL*Plus global variables to hold returned values. You can also useSQL*Plus substitution variables through the ampersand (&) and variablename. To view the result, use the SQL*Plus PRINT command.

Page 94: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!�%

Page 95: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!�&

�$�8�� ��������� � ���������

�$�8�� 3������ � ��� ����� ���

You can also call functions in SQL expressions. Anywhere a built-in SQL functioncan be placed, a PL/SQL user-defined function can be placed as well.

'�$������

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

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

Note: This feature is only available with PL/SQL 2.1 or higher and Oracle7 Serverrelease 7.1 or higher.

,��������

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

� The function acts as a single-row function.

� The function cannot contain a DML statement—the function cannot modifydatabase tables.

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

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

� The RETURN datatype must be an Oracle7 Server internal datatype.

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

Page 96: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!�)

Page 97: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!�*

�$�8�� ��������� � ���������

+����� � 3�����

You can call functions from any of these SQL clauses.

� The select list of a SELECT command

� The condition of a WHERE and HAVING clause

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

� The VALUES clause of the INSERT command

� The SET clause of the UPDATE command

40� ���

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

Page 98: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!�-

Page 99: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!�.

�� ��/

� Subprograms fall into three main categories:

� Procedures to perform actions

� Functions to compute a value

� Packages to bundle logically related procedures and functions

� A function differs from a procedure in two ways:

� You invoke the function as part of an expression.

� A function must return a value.

� Procedure and function components:

� Header—To name and type the block

� Declarative—To set up local identifiers (optional)

� Executable—To perform the actions

� Exception handling—To handle exceptions (optional)

� Invoke subprograms from the Procedure Builder Interpreter prompt.

Page 100: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!"�

Page 101: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!"1

�������� �$��$���

This practice guides you through creating a simple procedure and function andinvoking those functions from the Interpreter prompt.

�������� +�����

� Creating a simple procedure

� Debugging the procedure

� Executing the procedure

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

Page 102: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!"�

Page 103: OCP - SQL&PL_SQL(Vol3)

���������� ������ �� ���� ��������� � ��!""

�������� ��

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 “MyProcedure Works” to the screen.

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

b. Compile the code. Make appropriate corrections so code successfullycompiles.

c. Execute the procedure at the Interpreter prompt.

Page 104: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� �� ������ ���� ��������� ��������!"%

Page 105: OCP - SQL&PL_SQL(Vol3)

��������� ������ �����

�����

��

Page 106: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������

Page 107: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���

�!"�������

In this lesson, you create a simple PL/SQL block after learning the variouselements that compose a block.

At the end of this lesson, you should be able to

� Declare and use variables and constants in PL/SQL.

� Assign new values to variables within the executable section.

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

Page 108: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������#

Page 109: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���$

�������%

A PL/SQL block is comprised of up to three sections: declarative (optional),executable (required), and exception handling (optional). Only BEGIN and ENDkeywords 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 referencingvariables and other identifiers.

&����� '��!���

� Declare and initialize variables within the declaration section.

� Assign new values to variables within the executable section.

� Pass values into PL/SQL blocks through parameters.

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

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

Page 110: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������(

Page 111: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���)

������� ����� '��!��� �� *�������

You need to declare all identifiers within the declaration section before referencingthem within the PL/SQL block.

�+��,

identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];

where: identifier is the name of the identifier.

CONSTANT constrains the identifier so that its value cannotchange; constants must be initialized.

datatype is a scalar or composite datatype.

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

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

-���������

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

� You can use naming conventions, for example v_name to represent a variable, andc_name to represent a constant.

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

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

� Declare at most one identifier per line.

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

Page 112: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������.

Page 113: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���/

������� ���� '��!���

PL/SQL supports three datatypes—scalar, composite, and reference—that you canuse for declaring variables, constants, and pointers.

���� ���+���

A scalar datatype holds a single value and has no internal components. Scalardatatypes can be classified into four categories: number, character, date and time, orBoolean. Character and number datatypes have subtypes that associate a base type toa constraint. For example, INTEGER and POSITIVE are subtypes of the NUMBERbase type.

Datatype Description

BINARY_INTEGER Base type for integers between –2147483647and 2147483647.

NUMBER [(precision,scale)] Base type for fixed and floating point numbers.

CHAR [(maximum_length)] Base type for fixed length character data up to32767 bytes. If you do not specify amaximum_length, the default length is set to 1.

LONG Base type for variable length character data upto 32760 bytes.

LONG RAW Base type for binary data up to 32760 bytes.

VARCHAR2(maximum_length) Base type for variable length character data upto 32767 bytes.

DATE Base type for dates and times.

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

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

Page 114: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������0

Page 115: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� �����

������� ���� '��!��� ���������

1,�����

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 thevariable 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 oneweek from today.

v_order_date DATE := SYSDATE + 7;

Declare a constant for the tax rate, which never changes throughout the PL/SQLblock.

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 thevariable to TRUE.

v_valid BOOLEAN NOT NULL := TRUE;

Page 116: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ������������

Page 117: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ����

������� ���� '��!��� ���������

23� 425 1 6����!���

When you declare PL/SQL variables to hold column values, you must ensure that thevariable is of the correct datatype and precision. If it is not, then a PL/SQL error willoccur during execution.

Rather than hard-coding the datatype and precision of a variable, you can declare avariable according to another previously-declared variable or database column. Youdo this using the %TYPE attribute. To use the attribute in place of the datatyperequired in the variable declaration, prefix it with the database table and columnnames. If referring to a previously-declared variable, prefix the variable name to theattribute.

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 topopulate the variable.

6������ �7 ���� �3� 425 1 6����!���

� The datatype of the underlying database column may be unknown.

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

1,�����

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

...v_last_name s_emp.last_name%TYPE;v_first_name s_emp.first_name%TYPE;

...

Declare variables to store the balance for a checking account, as well as the minimumbalance, 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 databasecolumn defined as NOT NULL, you can assign the NULL value to the variable.

Page 118: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������#

Page 119: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ����$

������� *�������� ���+���

A composite datatype contains internal components and is reusable. Two types ofcomposite datatypes are available in PL/SQL: TABLE and RECORD.

����� 2!��

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

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

� A PL/SQL TABLE must contain two components:

� A primary key of datatype BINARY_INTEGER that indexes the PL/SQLTABLE.

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

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

Page 120: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������(

Page 121: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ����)

������� *�������� ���+��� ���������

������� ����� 2!���

1. Declare a TABLE datatype.

2. Declare a variable of that datatype.

�+��,

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.

1,����

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/SQLTABLE of that type. Do not initialize the PL/SQL TABLE.

Page 122: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������.

Page 123: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ����/

������� *�������� ���+��� ���������

����� 81*�8�

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

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

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

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

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

Page 124: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������0

Page 125: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� �����

������� *�������� ���+��� ���������

������� ����� 8������

1. Declare a RECORD datatype.

2. Declare a variable of that datatype.

�+��,

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 involvingoperators and functions.

identifier is the name of the identifier.

1,����

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 toinitialize NOT NULL fields.

Page 126: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ������������

Page 127: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ����

������� *�������� ���+��� ���������

������� 8������ %��3 �3� 48�925 1 6����!���

Declare a record based upon a collection of columns in a database table or view byusing the %ROWTYPE attribute. The fields within the record take their names anddatatypes from the columns of the table or view.

6������ �7 ���� �3� 48�925 1 6����!���

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

� The number and datatypes of the underlying database columns may change atruntime.

� Useful when retrieving a row with the SELECT statement.

1,����

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

...dept_record s_dept%ROWTYPE;

...

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

Page 128: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������#

Page 129: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ����$

����� ����� �+��, 8����

Because PL/SQL is an extension of SQL, the general syntax rules that apply to SQLare also applicable to the PL/SQL language.

-���������

� Identifiers can contain up to 30 characters, but they must start with an alphabeticcharacter.

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

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

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

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

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

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

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

For more information, seePL/SQL User’s Guide and Reference, Release 2.3, “Appendix E” for a list of reservedwords.

Page 130: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������(

Page 131: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ����)

����� ����� �+��, 8���� ���������

:����� ������

One of the advantages PL/SQL has over SQL is the ability to nest statements. Youcan nest blocks wherever an executable statement is allowed, thus making the nestedblock a statement. Therefore, you can break down the executable part of a block intosmaller blocks. The exception section can also contain nested blocks.

'��!�� �����

The scope of an object is the region of the program that can refer to the object. Youcan 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, itlooks up to the declarative section of the enclosing (or parent) blocks. The blocknever looks down to enclosed (or child) blocks or sideways to sibling blocks.

Scope applies to all declared objects, including variables, cursors, user-definedexceptions, and constants.

Page 132: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� �����������.

Page 133: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ����/

6������ '���� �� '��!���

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 theassignment operator (:=).

�+��,

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 ofthe PL/SQL TABLE and could also be avariable.

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 functioncall, but not a database column.

Page 134: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ���������� 0

Page 135: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ��� �

6������ '���� �� '��!��� ���������

1,�����

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

v_max_sal := v_sal;

Store the name “Maduro” in the index identifier of 3 in the PL/SQL TABLE of lastnames.

last_name_table (3) := ’Maduro’;

Store basic information for a new employee in a PL/SQL RECORD.

emp_record.last_name := ’Maduro’;emp_record.first_name := ’Elena’;emp_record.gender := ’F’;

Set the salary to the salary from the S_EMP table. This example produces a compileerror.

v_sal := s_emp.salary;

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

Page 136: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ���������� �

Page 137: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���

6������ '���� �� '��!��� ���������

*��� 1,������

Evaluate the PL/SQL block on the opposite page. Determine each of the followingvalues 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.

Page 138: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ���������� #

Page 139: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ��� $

6������ '���� �� '��!��� ���������

��������

The logical, arithmetic, and concatenation operators used in PL/SQL are the same asthose in SQL. In addition, there is an exponential operator (**).

You can control the order in which operations are performed by using parentheses, asin SQL.

1,�����

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);

Page 140: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ���������� (

Page 141: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ��� )

6������ '���� �� '��!��� ���������

;��������

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

� Single-row number functions

� Single-row character functions

� Datatype conversion functions

� Date functions

� Miscellaneous functions

Functions not available in procedural statements:

� GREATEST and LEAST

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

Group functions apply to groups of rows in a table, and are therefore available onlywithin SQL statements in a PL/SQL block.

1,�����

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.

Page 142: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ���������� .

Page 143: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ��� /

6������ '���� �� '��!��� ���������

���+�� *���������

Within an expression, you should make sure that datatypes are the same. If mixeddatatypes occur in the same expression, you should use the appropriate conversionfunction from the list below to convert the data.

�+��,

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.

1,�����

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

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

To correct the error, convert SYSDATE to a character string with the TO_CHARconversion function.

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

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

Page 144: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������#0

Page 145: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���#�

6������ '���� �� '��!��� ���������

8�7������� :��� ����� '��!���

You can reference variables declared in the host or calling environment in PL/SQLstatements, unless the statement is within a procedure, function, or package. Thisincludes host language variables declared in precompiler programs, screen fields in aDeveloper/2000 Forms application, and SQL*Plus bind variables.

To reference host variables, you must prefix the references with a colon (:) todistinguish them from declared PL/SQL variables.

1,����

Store the annual salary in a SQL*Plus global variable.

:g_annual_ salary := v_salary * 12;

Page 146: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������#�

Page 147: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���#

������� -���������

Adhere to programming guidelines for producing clear code and reducingmaintenance when developing a PL/SQL block.

-���������

� Document code with comments.

� Develop case conventions for the code.

� Develop naming conventions for identifiers and other objects.

� Indent code to enhance readability.

*�������� *���

Comment code to document each phase and to assist with debugging. Comment thePL/SQL code with two dashes (--) if the comment is on a single line, or enclose thecomment between the symbols /* and */ if the comment spans several lines.

1,����

Compute the yearly salary from the monthly salary.

... v_sal NUMBER(9,2);BEGIN/* Compute the annual salary based on the monthlysalary input from the user */ v_sal := v_sal*12;END;

Page 148: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������##

Page 149: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���#$

������� -��������� ���������

*��� *����������

A set of guidelines for writing code in uppercase or lowercase helps you todistinguish 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

*��� :��� *����������

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 substitutionparameter

p_name p_sal

SQL*Plus global variable g_name g_year_sal

Page 150: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������#(

Page 151: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���#)

������� -��������� ���������

����������

For clarity, indent each level of code. This enhances readability.

...BEGIN IF x=0 THEN y=1; END IF;...END;

Page 152: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������#.

Page 153: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���#/

�����+

����� ������

� Declaration section: optional

� Executable section: required

� Exception handling section: optional

����� ������7����

� Identifiers are defined in the declaration section.

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

� Definition can be a composite datatype with internal components, such as TABLEand RECORD.

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

� Identifiers created with NOT NULL or CONSTANT options require initialization.

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

*���������� 7�� ����������< 9�����< �� :��� *���

� Document code with comments.

� Develop conventions for writing text in uppercase and lowercase.

� Develop conventions for naming identifiers.

� Indent code to enhance readability.

Page 154: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������$0

Page 155: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���$�

������ �������%

This practice reinforces the basics of PL/SQL learned in this lesson, includingdatatypes, legal definitions of identifiers, and validation of expressions. You put allthese elements together to create a simple PL/SQL block using Oracle ProcedureBuilder.

������ *�������

� Determining validity of declarations

� Reviewing scoping and nesting rules

� Developing a simple subprogram in Oracle Procedure Builder

Page 156: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������$�

Page 157: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���$

������ ��

1. Evaluate each of the following declarations. Determine which of them are notlegal and explain why.

DECLARE v_id NUMBER (4);

a.

DECLARE v_x, v_y, v_z VARCHAR2(10);

b.

DECLARE v_birthdate DATE NOT NULL;

c.

DECLARE v_in_stock BOOLEAN := 1;

d.

DECLARE emp_record emp_record_type;

e.

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

f.

Page 158: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������$#

������ �� ���������

2. Suppose you embed a sub-block within a block, as depicted below. You declaretwo 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

����� 1,����

DECLARE v_customerNUMBER (7) := 201;

v_name VARCHAR2(25):= ’Unisports’;

�1-�: v_customer v_name v_credit_rating

1:�=

�1*�681 v_customer VARCHAR2(50) := ’Womansport’;

v_credit_rating VARCHAR2(10) := ’EXCELLENT’;

�1-�:�������*>

v_customer v_name v_credit_rating

1:�=

Page 159: OCP - SQL&PL_SQL(Vol3)

��������� ������ ����� ����� ���$$

������ �� ���������

3. Create and execute a procedure named MULTIPLIER that accepts two numbersthrough variables. The first number should be divided by the second number andhave the second number added to the result. The result should be written to aPL/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 forone year. The annual salary and the annual bonus percentage will be passed to thefunction, and the bonus will need to be converted from a whole number to adecimal (for example, 15 to .15). If the salary is null, set it to zero beforecomputing the total compensation. Likewise, if the bonus is null, set it to zerobefore computing the total compensation. Execute the function. Reminder: Usethe NVL function to handle null values.

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

Page 160: OCP - SQL&PL_SQL(Vol3)

������������ �� ������ ��� �� ����� ���� �������� ����������$(

Page 161: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� �

��

Page 162: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� �������

Page 163: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ����

����������

In this lesson, you access the database and control transactions through SQLstatements in PL/SQL.

At the end of this lesson, you should be able to

� Use SELECT, INSERT, UPDATE, and DELETE commands in PL/SQLsubprograms.

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

� Control transactions within PL/SQL.

Page 164: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ������

Page 165: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ���!

�������

When you need to extract information from or apply changes to the database, youmust use SQL. PL/SQL supports full data manipulation language and transactioncontrol commands within SQL. You can use SELECT statements to populatevariables with values queried from a row in a table. Your DML commands canprocess multiple rows.

"�#$���� ��� ��� ������ �����#��� %&$��

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

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

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

� DBMS_SQL package allows you to issue DDL and DCL statements.

Page 166: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ������'

Page 167: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ���(

)�������� *��� ���� ������

Use the SELECT statement to retrieve data from the database. The SELECTstatement contains an additional mandatory clause: the INTO clause. In the INTOclause, list the output variables for receiving the data. The SELECT statement mustreturn exactly one row or an error will occur.

+������ �&���,

SELECT select_listINTO variable_name | record_nameFROM tableWHERE condition;

where: select_list is a list of at least one column, and can includeSQL expressions, row functions, or groupfunctions.

variable_name is the scalar variable to hold the retrieved value.

record_name is the PL/SQL RECORD to hold the retrievedvalues.

table specifies the database table name.

condition is composed of column names, expressions,constants, and comparison operators, includingPL/SQL variables and constants.

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

-���� ����

� Terminate each SQL statement with a semicolon (;).

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

� The INTO clause is required for the SELECT statement when it is embeddedwithin PL/SQL.

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

Page 168: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ������.

Page 169: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ���/

)�������� *��� ���� ������ ���������

-���� ����

� Specify the same number of output variables in the INTO clause as databasecolumns in the SELECT clause. Be sure that they correspond positionally and thattheir datatypes are compatible.

� Ensure that the datatype of the identifiers match the datatype of the columns byusing the %TYPE attribute. The datatype and number of variables in the INTOclause match those in the SELECT list.

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

� Include at least one RETURN statement in a function.

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

Page 170: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ������01

Page 171: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ���00

)�������� *��� ���� ������ ���������

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

Page 172: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ������0�

Page 173: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ���0�

)�������� *��� ���� ������ ���������

Avoid ambiguity in the WHERE clause by adhering to a naming convention thatdistinguishes database column names from PL/SQL variable names.

2,�#$ �

Retrieve the order date and the ship date for the specified order. This example raisesan unhandled runtime exception.

PROCEDURE order_info(id s_ord.id%TYPE)

ISdate_ordered s_ord.date_ordered%TYPE;date_shipped s_ord.date_shipped%TYPE;

BEGINSELECT 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 assumedto be a PL/SQL identifier.

Page 174: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ������0

Page 175: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ���0!

�2�2"% 2,��$�����

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

�2�2"% 2,��$�����

Condition Exception

The SELECT statement identifies morethan one row.

TOO_MANY_ROWS exception(Oracle7 Server error number -1422).

The SELECT statement does not identifyany rows.

NO_DATA_FOUND exception (Oracle7Server error number +1403).

Note: Handle the raised exceptions with exception-handling routines, which will becovered in a later lesson. Alternatively, fetch multiple rows one-by-one in aloop by declaring an explicit cursor.

Page 176: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ������0'

Page 177: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ���0(

�2�2"% 2,��$����� ���������

%��34+563)�7� 2,��$����

When more than one record is identified with a SELECT statement, Oracle7 Serverraises an error number -1422, also referred to as TOO_MANY_ROWS, which is thepredefined exception name.

5�3*+%+38��5* 2,��$����

When no rows are identified with a SELECT statement, the NO_DATA_FOUNDexception 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.

Page 178: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ������0.

Page 179: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ���0/

4���$� ���� *��� ���� ������

Manipulate data in the database by using the DML commands.

� INSERT statement adds new rows of data to the table.

� UPDATE statement modifies existing rows in the table.

� DELETE statement removes unwanted rows from the table.

�������� *���

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

� Use SQL function, such as USER and SYSDATE.

� Generate primary key values by using database sequences.

� Derive values in the PL/SQL block.

� Add column default values.

Page 180: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� �������1

Page 181: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ����0

4���$� ���� *��� ���� ������ ���������

�$����� ��� *� ���� *���

There may be ambiguity in the SET clause of the UPDATE statement becausealthough the identifier on the left of the assignment operator is always a databasecolumn, the identifier on the right can be either a database column or a PL/SQLvariable.

Remember that the WHERE clause is used to determine which rows are affected. Ifno rows are modified, no error occurs, unlike the SELECT statement in PL/SQL.

Page 182: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ��������

Page 183: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � �����

��� "�����

Whenever you issue a SQL command, the Server opens an area of memory in whichthe 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 animplicit cursor, which has the SQL identifier. PL/SQL manages this cursorautomatically. 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.

��� "����� +���������

You can use these attributes in PL/SQL statements as you would functions, but not inSQL commands. They are useful to evaluate the result of a DML operation. PL/SQLdoes not consider a data manipulation language statement that affects no rows to havefailed, unlike the SELECT statement, which returns an exception.

Attribute Description

SQL%ROWCOUNT Number of rows affected by the most recent SQLstatement (an integer value).

SQL%FOUND Boolean attribute that evaluates to TRUE if the mostrecent SQL statement affects one or more rows.

SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the mostrecent SQL statement does not affect any rows.

SQL%ISOPEN Always evaluates to FALSE because PL/SQL closesimplicit cursors immediately after they are executed.

For more information, seePL/SQL User’s Guide and Reference, Release 2.3, Chapter 4, “Implicit CursorAttributes” section.

Page 184: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� �������

Page 185: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ����!

��� "����� +��������� ���������

2,�#$ �

Write a procedure to delete rows that have the specified order number from the itemtable. 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;

Page 186: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� �������'

Page 187: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ����(

"����� �� %�����������

Control the logic of transactions with COMMIT and ROLLBACK SQL commands,rendering some groups of database changes permanent, while discarding others. Aswith Oracle7, DML transactions start at the first command to follow a COMMIT orROLLBACK, and end on the next successful COMMIT or ROLLBACK. Theseactions may occur within a PL/SQL block or as a result of events in the hostenvironment (for example, ending a Procedure Builder session automatically commitsthe pending transaction).

You can also include explicit locking commands (such as LOCK TABLE andSELECT ... FOR UPDATE) in a block. They take effect until the end of thetransaction.

"�44�% "�##���

COMMIT ends the current transaction by making all pending changes to the databasepermanent.

�&���,

COMMIT [WORK];

where: WORK is for compliance with ANSI standards.

)����+"9 "�##���

ROLLBACK ends the current transaction by discarding all pending changes.

�&���,

ROLLBACK [WORK];

where: WORK is for compliance with ANSI standards.

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

Page 188: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� �������.

Page 189: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ����/

"����� �� %����������� ���������

�+:2���5% "�##���

Alter the transactional logic with Oracle7 Server savepoints based upon runtimeconditions. SAVEPOINT marks an intermediate point in the transaction processing.

�&���,

SAVEPOINT savepoint_name;

ROLLBACK TO SAVEPOINT discards pending changes made after the savepointwas marked.

�&���,

ROLLBACK [WORK] TO [SAVEPOINT] savepoint_name;

where: savepoint_name is a PL/SQL identifier.

Page 190: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� �������1

Page 191: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ����0

��##��&

You can embed SQL within the PL/SQL block. You can use the following validcommands:

Statement Description

SELECT Retrieves exactly one row into scalar variables or into arecord 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 TOSAVEPOINT

Eliminates all pending transactions since the namedsavepoint.

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

Page 192: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� ��������

Page 193: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � �����

�������� �������

In this practice, you create three procedures to input, update, and delete informationin a table, all using DML statements within a PL/SQL block.

�������� "�������

� Creating a procedure to insert data into a table

� Creating a procedure to update data in a table

� Creating a procedure to delete a record from a table

� Verifying your changes to the table using Oracle Procedure Builder built-ins andimplicit cursor attributes

Page 194: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� �������

Page 195: OCP - SQL&PL_SQL(Vol3)

���������� ��� ���� � ����!

�������� ��

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

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

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

d. Test the procedure. What happens if you enter a region name that does notexist?

e. Display the department number, region number, and region name for theupdated department.

3. 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 doesnot exist?

What happens if you enter a department that has employees?

d. Confirm that the department has been deleted.

Page 196: OCP - SQL&PL_SQL(Vol3)

������������ �� ���� �� ��� ��� ������ ���� ��������� ��� �������'

�������� �� ���������

If you have time, complete the following exercise.

4. Create a procedure named NEW_EMP to insert a new employee into the S_EMPtable.

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

Page 197: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ���

������

��

Page 198: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� �����������

Page 199: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ����

�� ����!��

You can control the flow of your PL/SQL block by using conditional statementsand loops.

At the end of this lesson, you should be able to

� Conditionally control processing in a PL/SQL block.

� Iterate statements by using various types of loops.

Page 200: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ����������"

Page 201: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ���#

�!��!��

You can change the logical flow of statements within the PL/SQL block with anumber of control structures. This lesson addresses two types of PL/SQL controlstructures:

� Conditional constructs with the IF statement

� Looping constructs

� Basic loop to provide repetitive actions without overall conditions

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

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

� EXIT statement to terminate loops

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

Page 202: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ����������$

Page 203: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ���%

&'� � �����(���

The structure of the PL/SQL IF statement is similar to the structure of IF statementsin other procedural languages. It allows PL/SQL to perform actions selectively basedupon conditions.

�)���*

IF condition THEN statements;[ELSIF condition THEN statements;][ELSE statements;]END IF;

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

+���������

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

� ELSIF is one word.

� END IF is two words.

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

� Any number of ELSIF clauses are permitted.

� There can be at most one ELSE clause.

� Indent the conditionally executed statements for clarity.

Page 204: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ����������,

Page 205: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ���-

&'� � �����(��� ���������

��(.�� � �����(����

PL/SQL executes the conditional statements only if the condition is TRUE. If thecondition is FALSE or NULL, then PL/SQL ignores the conditional statements. Ineither case, control resumes at the next statement in the program following END IF.

/*�(.��

Set the job title to Sales Representative and the region number to 35 if the last nameis Dumas.

. . .IF v_last_name = ’Dumas’ THEN v_job := ’Sales Representative’; v_region_id := 35;END IF;. . .

��&0/1�/��/ �����(����

If the condition is FALSE or NULL, you can use the ELSE clause to carry out otheractions. As with the simple IF statement, control resumes in the program from theEND IF.

/*�(.��

Set a flag for orders where there are fewer than five days between order date and shipdate.

. . .IF v_date_shipped - v_date_ordered < 5 THEN v_ship_flag := ’Acceptable’;ELSE v_ship_flag := ’Unacceptable’;END IF;. . .

Page 206: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ����������23

Page 207: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ���22

&'� � �����(��� ���������

1����� � �����(����

Either set of actions of the result of the first IF statement can include further IFstatements before specific actions are performed. Each nested IF statement must beterminated with a corresponding END IF.

��&0/1�/��� �����(����

When possible, however, use the ELSIF clause instead of nesting IF statements. Thecode is easier to read and understand. The logic is clearly identified. If the action inthe ELSE clause consists purely of another IF statement, it is more convenient to usethe ELSIF clause. This makes the code clearer by removing the need for nested ENDIFs at the end of each further set of conditions and actions.

/*�(.��

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 isbetween 50 and 100, then the calculated value is 50% of the starting value. If theentered value is less than 50, then the calculated value is 10% of the starting value.

FUNCTION calc_val (v_start IN NUMBER)RETURN NUMBERISBEGIN 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;

Page 208: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ����������2�

Page 209: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ���2�

�������� ������� ����������

Build a simple Boolean condition by combining number, character, or dateexpressions with a comparison operator. In general, handle null values with the ISNULL operator.

1��� 4��'�� /*.�������� ��� ��(.�������

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

� Any simple comparison containing a null value evaluates to NULL.

� An IS NULL comparison evaluates to TRUE or FALSE.

������� ���������� ��' ������� �.�������

Build a complex Boolean condition by combining simple Boolean conditions with thelogical operators AND, OR, and NOT. In the accompanying logic tables, FALSEtakes precedence for an AND condition and TRUE takes precedence in an ORcondition.

Page 210: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ����������2"

Page 211: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ���2#

�������� ������� ���������� ���������

The AND logic table can help you evaluate the possibilities for the Boolean conditionyou see below.

. . .v_flag := v_reorder_flag AND v_available_flag;. . .

Page 212: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ����������2$

Page 213: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ���2%

���. �����(����

PL/SQL provides a number of facilities to structure loops to repeat a statement orsequence of statements multiple times.

����� ���.

The simplest loop consists of the body of statements to be repeated enclosed betweenthe delimiters LOOP and END LOOP. Each time the flow of execution reaches theEND LOOP statement, control is returned to the corresponding LOOP statementabove it. This uncontrolled loop is an infinite loop that is to be avoided. To avoid aninfinite loop, add an EXIT statement.

&'� /5�& �����(���

You can terminate a loop using the EXIT statement. Control passes to the nextstatement after the END LOOP statement. You can issue EXIT either as an actionwithin 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.

�)���*

LOOP statement1; statement2; . . . EXIT [WHEN condition];END LOOP;

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

Page 214: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ����������2,

Page 215: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ���2-

���. �����(���� ���������

/*�(.��

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

Page 216: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� �����������3

Page 217: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ����2

���. �����(���� ���������

�6 ���.

FOR loops have the same general structure as the loops you have already seen. Inaddition, they have a control statement at the front of the LOOP keyword todetermine the number of iterations PL/SQL performs.

�)���*

FOR index IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP;

where: index is an implicitly declared integer whose valueautomatically increases or decreases by 1 oneach iteration of the loop until the upper boundis reached.

REVERSE causes the index to decrement with eachiteration from the upper bound to the lowerbound.

lower_bound specifies the lower bound for the range of indexvalues.

upper_bound specifies the upper bound for the range of indexvalues.

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

Page 218: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ������������

Page 219: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ �����

���. �����(���� ���������

/*�(.��

Print the number of times the loop is executed and the last value for the index basedon 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;

+���������

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

� Reference the existing value of an index within an expression.

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

Page 220: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� �����������"

��������� ���!������� �� �'���������� �7���' ���������8

Page 221: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ����#

���. �����(���� ���������

40��/ ���.

You can use the WHILE loop to repeat a sequence of statements until the controllingcondition 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 thestart of the loop, then no further iterations are performed.

�)���*

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.

Page 222: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� �����������$

Page 223: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ����%

���. �����(���� ���������

1����� ���.� ��� ������

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 doesnot terminate the enclosing loop (unless an exception was raised). However, you canlabel loops and exit the outer loop with the EXIT statement.

Label names follow the same rules as other identifiers. A label is placed before astatement, either on the same line or a separate line. Label loops by placing the labelbefore the word LOOP within label delimiters (<<label>>).

If the loop is labeled, the label name can optionally be included after the END LOOPstatement.

...BEGIN<<Outer–loop>>LOOP v_counter :=v_counter+1; EXIT WHEN v_counter>10; <<Inner–loop>>LOOP ... EXIT Outer_loop WHEN total_done = ’YES’; –– Leave both loops EXIT WHEN inner_done = ’YES’; –– Leave inner loop only ... END LOOP Inner_Loop; ...END LOOP Outer_loop;END;

Page 224: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� �����������,

Page 225: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ����-

��((��)

Control PL/SQL logic with the conditional structure and loops.

Control Structure Description

IF-THEN-ELSE Executes a statement or sequence of statementsconditionally.

Basic loop Repeats a statement or sequence of statementsindefinitely.

EXIT statement Terminates a loop.

FOR loop Repeats a statement or sequence of statements a fixednumber of times.

WHILE loop Repeats a statement or sequence of statements until acondition is no longer TRUE.

Page 226: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� �����������3

Page 227: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ ����2

�������� �!��!��

In this practice, you create procedures that incorporate loops and conditional controlstructures.

�������� ��������

� Performing conditional actions using the IF statement

� Performing iterative steps by using the loop structure

� Viewing the values variables during runtime by using Procedure Builderdebugging features

Page 228: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� ������������

Page 229: OCP - SQL&PL_SQL(Vol3)

����������� �� �� �� ��� ������ �����

�������� ��

If you are not already connected to the database, be sure to do so now.

1. Create a procedure named SET_COMM to conditionally set the commissionpercentage for a given employee based upon total sales.

a. Prepare this exercise by disabling the constraint on the COMMISSION_PCTcolumn in the S_EMP table. You modify the commission percentage to valuesthat are not in the constraint.

PL/SQL> ALTER TABLE s_emp +> DROP CONSTRAINT s_emp_commission_pct_ck;

b. Create a parameter to accept the employee number from the user.

c. Find the sum of the totals for all orders placed by that employee.

d. If the sum is less than 100,000, set the commission percentage for theemployee to 10.

e. If the sum is between 100,000 and 1,000,000 inclusive, set the commissionpercentage for the employee to 15.

f. If the sum exceeds 1,000,000, set the commission percentage for theemployee to 20.

g. If no orders appear in the S_ORD table for the given employee, set thecommission percentage to 0.

h. Commit the change.

i. Test the block and view the changes. Results should appear for some exampleemployees as follows:

Employee Number Total Sales Resulting Commission--------------- ------------ ---------------------

1 0 011 1629066.37 2012 100184.00 1514 16358.00 10

Page 230: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� ��� ��� �� ��� ����� ��������� �����������"

�������� �� ���������

2. Write a procedure named CUST_UPDATE that loops through the region numbers(1 through 5) to update the credit rating of all customers. Do not issue a commit.

a. If the region number is even, then set the credit rating to Excellent (even if thecustomer’s credit rating is already Excellent), otherwise set the credit rating toGood.

b. Once the rows are updated, find out how many rows were updated. Print thefollowing statements to the screen based on the number of rows updated.

i. If less than three rows updated, statement should read “Fewer than 3customer records updated for region number X”, where X represents theregion number.

ii. Otherwise, it should read “Y rows updated for region number X”, where Yis the number of rows updated, and X is the region number.

c. Rollback the changes. Set a breakpoint on the conditional test for the numberof rows updated. Execute the procedure. Check the Stack node to verify thevalues of the variables as you Step Into the statements in the loop.

Reminder: You can use the Quick Tour, “Debugging a Program Unit” sectionfor assistance.

If you have time, complete the following exercise.

3. Create a procedure named EMP_MESSAGE that selects the employee last name,start date, and salary based on an employee number provided at execution. Print amessage to the screen based on any combination of one of the following criteria.Test employee numbers 2, 5, 16, 17, and 18. Hint: A nested IF is required.

Criteria Message

Salary greater than 1200 Salary more than 1200

Last name contains “R” Name contains “R”

Start date is in March March start date

None of the above **None**

Page 231: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ����

�������� �������

��

Page 232: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� �

Page 233: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� !

��"����#��

You may need to use a multiple row SELECT statement within PL/SQL toprocess many rows. To accomplish this, you declare and control explicit cursors,which are used in loops, including the cursor FOR loop.

At the end of this lesson, you should be able to

� Explain the difference between implicit and explicit cursors.

� Declare and use explicit cursors to fetch rows from the database.

� Create an explicit cursor containing parameters.

� Write cursor FOR loops.

Page 234: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� �

Page 235: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� $

�#��#��%

The Oracle7 Server uses work areas called “private SQL areas” to execute SQLstatements and store processing information. PL/SQL cursors let you name a privateSQL area and access its stored information. The cursor directs all phases ofprocessing.

Cursor Type Description

Implicit Declared by PL/SQL implicitly for all DML and PL/SQLSELECT statements.

Explicit Declared and named by the programmer and manipulatedthrough specific statements within the block’s executableactions.

Recall that the SELECT statement in PL/SQL must only return a single row. PL/SQLactually attempts to fetch two rows from an implicit cursor: one to satisfy the query,and a second to see if further rows were returned. One method to eliminate this extrafetch is to use an explicit cursor.

�������� ������ &��������

� Can process beyond the first row returned by the query, row by row.

� Keep track of which row is currently being processed.

� Allow the programmer to manually control them in the PL/SQL block.

Page 236: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� '

Page 237: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� (

���������� �������� �������

Now that you have a conceptual understanding of cursors, review the steps to usethem. The syntax for each step follows on the next pages.

���������� �������� ������� ���� &��� ��))����

1. Declare the cursor.

Declare the cursor by naming it and defining the structure of the query to beperformed within it.

2. Open the cursor.

The OPEN statement executes the query and binds any variables that arereferenced. Rows identified by the query are called the active set and are nowavailable for fetching.

3. Fetch data from the cursor.

The FETCH statement loads the current row from the cursor into variables. Eachfetch causes the cursor to move its pointer to the next row in the active set.Therefore, each fetch will access a different row returned by the query.

In the flow diagram on the left page, each fetch tests the cursor for any existingrows. If rows are found, it loads the current row into variables, else it closes thecursor.

4. Close the cursor.

The CLOSE statement releases the active set of rows. It is now possible to reopenthe cursor to establish a fresh active set.

Page 238: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� *

Page 239: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� +

���������� �������� ������� ���������

,������� �-� ������

Use the CURSOR statement to declare an explicit cursor. You can define parametersto allow substitution of values into the query when the cursor is opened. You can alsoreference variables within the query, but you must declare them before the cursorstatement.

� ����

DECLARE CURSOR cursor_name IS

select_statement;

where: cursor_name is a PL/SQL identifier.

select_statement is a SELECT statement without an INTOclause.

Note: Do not include the INTO clause within the cursor declaration because itappears later within the FETCH statement.

.

Page 240: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� ./

Page 241: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� ..

���������� �������� ������� ���������

������ �-� ������

Open the cursor to execute the query and identify the active set after specifyingvalues for all input variables. The cursor will now point to the first row in the activeset.

� ����

OPEN cursor_name;

where: cursor_name is the name of the previously-declared cursor.

Note: If the query returns no rows when the cursor is opened, PL/SQL does not raisean exception. However, you can test the cursor’s status after a fetch.

Page 242: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� .�

Page 243: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� .!

���������� �������� ������� ���������

&���-�� ,��� 0��) �-� ������

Use the FETCH statement to retrieve the current row values into output variables.After the fetch, you can manipulate the variables by further statements.

� ����

FETCH cursor_name INTO variable1, variable2, . . .;

where: cursor_name is the name of the previously declared cursor.

variable is an output variable to store the results.

1���������

� Include the same number of variables within the INTO clause of the FETCHstatement as output columns in the SELECT statement, and be sure that thedatatypes are compatible.

� Match each variable to correspond to the columns positionally.

� Alternatively, define a record for the cursor and reference the record in theFETCH INTO clause.

� Test to see if the cursor contains rows. If a fetch acquires no values, that is, thereare now rows left to process in the active set and no error is recorded.

!

Page 244: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� .�

Page 245: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� .$

���������� �������� ������� ���������

������ �-� ������

Close the cursor after completing the processing of the SELECT statement. This stepallows the cursor to be reopened, if required. Therefore, you can establish an activeset several times.

� ����

CLOSE cursor_name;

where: cursor_name is the name of the previously declared cursor.

Note: Do not attempt to fetch data from a cursor once it has been closed or theINVALID_CURSOR exception will be raised.

Page 246: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� .'

Page 247: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� .(

�������� ������ 2���������

As with implicit cursors, there are four attributes for obtaining status informationabout a cursor. When used, the attribute name is preceded by the cursor identifier.

Cursor Attribute Description

%ISOPEN Boolean attribute that evaluates to TRUE if the cursor isopen.

%NOTFOUND Boolean attribute that evaluates to TRUE if the most recentfetch does not return a row.

%FOUND Boolean attribute that evaluates to TRUE until the mostrecent fetch does not return a row; complement of%NOTFOUND.

%ROWCOUNT Numeric attribute that evaluates to the total number of rowsreturned so far.

Note: Do not reference cursor attributes directly within a SQL statement.

���������� 3������� &���-�� 0��) �������� �������

Typically, when you want to process several rows from an explicit cursor, you definea loop to perform a fetch on each iteration. Eventually, all rows in the active set willbe processed, and an unsuccessful fetch sets the %NOTFOUND attribute to TRUE.Use the explicit cursor attributes to test success of each fetch before any furtherreferences are made to the cursor. If you omit an exit criteria, an infinite loop willresult.

For more information, seePL/SQL User’s Guide and Reference, Release 2.3 “Using Cursor Attributes” section.

Page 248: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� .*

Page 249: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� .+

�������� ������ 2��������� ���������

You can only fetch rows when the cursor is open. Determine whether the cursor isopen using the %ISOPEN cursor attribute, if necessary.

Fetch rows in a loop. Determine when to exit the loop by using cursor attributes.

To retrieve an exact number of rows, fetch the rows in a numeric FOR loop, or fetchthe rows in a simple loop and determine when to exit the loop by using the%ROWCOUNT cursor attribute.

���)���

Retrieve the first five line items for an order one by one. Print the cumulative total foreach product to the screen.

PROCEDURE ord_process (v_ord_id IN s_item.ord_id%TYPE)IS v_product_id s_item.product_id%TYPE; v_item_total NUMBER (11,2); v_order_total NUMBER (11,2) := 0; CURSOR item_cursor IS

SELECT product_id, price * quantityFROM s_itemWHERE ord_id = v_ord_id;

BEGIN OPEN item_cursor; LOOP FETCH item_cursor INTO v_product_id, v_item_total; EXIT WHEN item_cursor%ROWCOUNT > 5 OR item_cursor%NOTFOUND; v_order_total := v_order_total + v_item_total; TEXT_IO.PUT_LINE (’Product ID ’|| TO_CHAR(v_product_id)|| ’ has a total of ’|| TO_CHAR(v_order_total,’$999,999,999.99’)); END LOOP; CLOSE item_cursor;END ord_process;

Note: If using %ROWCOUNT, add a test for no rows in the cursor by using the%NOTFOUND attribute because the rowcount is not incremented if the fetchdoes not retrieve any rows.

Page 250: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� �/

Page 251: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� �.

������� ��� 4������

We have already seen that you can define records to use the structure of columns in atable. You can also define a record based on the selected list of columns in an explicitcursor. This is convenient for processing the rows of the active set since you cansimply fetch into the record. Therefore, the values of the row are loaded directly intothe corresponding fields of the record.

In the example, you can select the ROWID pseudo-column, and it will have acorresponding field within the EMP_RECORD PL/SQL record.

Page 252: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� ��

Page 253: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� �!

������� %��- ����)�����

Parameters allow values to be passed to a cursor when it is opened, and used withinthe query when it executes. This means that you can open an explicit cursor severaltimes in a block, returning a different active set on each occasion.

Parameter datatypes are the same as those for scalar variables, but you do not givethem sizes. The parameter names are for references within the cursor’s queryexpression.

� ����

CURSOR cursor_name [(parameter_name datatype, ...)] IS select_statement;

where: cursor_name is a PL/SQL identifier for the previouslydeclared cursor.

parameter_name is the name of a parameter.

datatype is a scalar datatype of the parameter.

select_statement is a SELECT statement without the INTOclause.

When the cursor is opened, you pass values to each of the parameters positionally.You can pass values from PL/SQL or host variables as well as literals.

Page 254: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� ��

Page 255: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� �$

������ &�4 �����

A cursor FOR loop processes rows in an explicit cursor. It is a shortcut because thecursor is opened, rows are fetched once for each iteration in the loop, and the cursoris closed automatically when all rows have been processed. The loop itself isterminated automatically at the end of the iteration where the last row was fetched.

� ����

FOR record_name IN cursor_name LOOP statement1; statement2; . . .END LOOP;

where: record_name is the name of the implicitly-declared record.

cursor_name is a PL/SQL identifier for thepreviously-declared cursor.

1���������

� Do not declare the record that controls the loop. Its scope is only in the loop.

� Test the cursor attributes during the loop, if required.

� Supply the parameters for a cursor, if required, in parentheses following thecursor name in the FOR statement.

� Do not use a cursor FOR loop when the cursor operations have to be handledmanually.

Page 256: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� �'

Page 257: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� �(

2��� �� �-� 56�4� ��44�78 �& ������

You may want to lock rows before you update or delete rows. Add the FOR UPDATEclause within the cursor query, which locks the affected rows when the cursor isopened. Since the Oracle7 Server releases locks at the end of the transaction, youshould not commit across fetches from an explicit cursor if FOR UPDATE is used.

� ����

SELECT...FROM...FOR UPDATE [OF column_reference] [NOWAIT]

where: column_reference is a column in the table against which the queryis performed.

NOWAIT returns an Oracle error if the rows are locked byanother session.

When querying multiple tables, you can use the FOR UPDATE clause to confine rowlocking to particular tables. Rows in a table are locked only if the FOR UPDATEclause refers to a column in that table.

56�4� ��44�78 �& ������

Additionally, you can write your DELETE or UPDATE statement to contain theWHERE CURRENT OF cursor_name clause to refer to the latest row processed bythe FETCH statement. When you use this clause, the cursor you reference must existand must contain the FOR UPDATE clause in the cursor query, otherwise you willobtain an error. This clause allows you to apply updates and deletes to the currentlyaddressed row without the need to explicitly reference the ROWID pseudo-column.

Page 258: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� �*

Page 259: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� �+

��))��

������ 8 ���

� Implicit cursors are used for all DML statements and single row queries.

� Explicit cursors are used for queries of zero, one, or more rows.

�������� ������ ��))����

� Declare the cursor.

� Open the cursor.

� Fetch data from the cursor.

� Close the cursor.

������ 2���������

Evaluate the status of the cursor by using cursor attributes.

������� %��- ����)�����

Use parameters to open an explicit cursor several times in a block, returning adifferent active set on each occasion.

������ &�4 �����

Use cursor FOR loops as a shortcut to open the cursor, fetch rows once for each loopiteration, and automatically close the cursor after all rows are processed.

Page 260: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� !/

Page 261: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� !.

�������� �#��#��%

This practice applies your knowledge of cursors to process a number of rows from atable and populate another table with the results using a cursor FOR loop.

�������� ��������

� Declaring and using a cursor to query rows of a table

� Using a cursor FOR loop

� Applying cursor attributes to test the cursor status

Page 262: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� !�

Page 263: OCP - SQL&PL_SQL(Vol3)

��������� ������ � ���� �������� ������� �� !!

�������� ��

1. Create a procedure named TOP_DOGS1 that determines the top employees withrespect to salaries.

a. Prepare for this exercise by creating a new table for storing employees andtheir salaries.

PL/SQL> CREATE TABLE top_dogs +> (name VARCHAR2(25), +> salary NUMBER(11,2));

b. Add a parameter to accept the user input n for the top number of employees.

c. Write a cursor FOR loop to get the last names and salaries of the top n people,with respect to salary, from the S_EMP table.

d. Store the names and salaries in the TOP_DOGS table.

e. Assume for the moment that no two employees have the same salary.

f. Test the exercise under a variety of special cases, such as n = 0, n is greaterthan the number of employees in the S_EMP table.

g. Empty the TOP_DOGS table after each test.

2. Create a stored procedure named ADD_STARS to reward all employees byappending an asterisk in the STARS column for every commission point.

a. Prepare for this exercise by creating a new column in the S_EMP table forstoring asterisks (*).

PL/SQL> ALTER TABLE s_emp +> ADD stars VARCHAR2(100);

b. Determine the commission percentage for the employee, rounded to thenearest whole number. Also, consider the case where the employee has nocommission percent.

c. Add an asterisk to a string of asterisks for every commission point. Forexample, if the employee has a commission percentage of 10, then the STARScolumn will contain ten asterisks.

d. Update the STARS column for each employee with the string of asterisks.

Page 264: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ����� ���� ��������� ��������� !�

�������� �� ���������

If you have time, complete the following exercise.

3. Copy the TOP_DOGS1 procedure from exercise 1, and name it TOP_DOGS2.Modify the TOP_DOGS2 procedure to consider the case where severalemployees in the exercise 1 have the same salary. For each name listed, all nameshaving the same salary should also be listed.

Execute the TOP_DOGS2 procedure. Enter 6, 7, or 8 for n, then Ngao, Dumas,and Quick-To-See should all display. If you enter 9, 10, or 11 for n, thenNagayama, Magee, and Maduro should all display.

Remember to empty the TOP_DOGS table after each test.

Page 265: OCP - SQL&PL_SQL(Vol3)

����� ������

��

Page 266: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ����������

Page 267: OCP - SQL&PL_SQL(Vol3)

����� ������ ����

������ ��

When you execute PL/SQL code, you may encounter errors. Errors cause thePL/SQL block to halt with an exception. You can trap the exception andperform actions conditionally using exception handlers.

At the end of this lesson, you should be able to

� Identify common exceptions.

� Describe the three basic types of exceptions.

� Write exception handling routines.

Page 268: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ���������!

Page 269: OCP - SQL&PL_SQL(Vol3)

����� ������ ����

� �� �"

An exception is an identifier in PL/SQL, raised during the execution of a block thatterminates its main body of actions. A block will always terminate when PL/SQLraises an exception, but you specify an exception handler to perform final actions.

#"� $��%��� &�� '��� �� �(��)���

� An Oracle error occurs and the associated exception is raised automatically. Forexample, if the error ORA-01403 occurs when no rows are retrieved from thedatabase, then PL/SQL raises the exception NO_DATA_FOUND.

� You raise an exception explicitly by issuing the RAISE statement within theblock. The exception being raised may be either user-defined or predefined.

#��))� �� �(��)���

If the exception is raised in the executable section of the block, processing branchesto the corresponding exception handler in the exception section of the block. IfPL/SQL successfully handles the exception, then the exception does not propagate tothe enclosing block or environment.

���)���� �� �(��)���

The other method for handling an exception is to allow it to propagate to the callingenvironment. If the exception is raised in the executable section of the block andthere is no corresponding exception handler, the PL/SQL block terminates withfailure.

Page 270: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ���������*

Page 271: OCP - SQL&PL_SQL(Vol3)

����� ������ ���+

�(��)��� #,)��

You can program for exceptions to avoid disruption at runtime. There are three typesof exceptions.

Exception Description Directions for Handling

Predefined Oracle7Server error

One of approximately 20most errors that occuroften in PL/SQL code.

Do not declare, and allow theOracle7 Server to raise themimplicitly.

Non-PredefinedOracle7 Servererror

Any other standardOracle7 Server error.

Declare within the declarativesection, and allow the Oracle7Server to raise them implicitly.

User-defined error A condition that thedeveloper determines isabnormal.

Declare within the declarativesection, and raise explicitly.

Page 272: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ���������-

Page 273: OCP - SQL&PL_SQL(Vol3)

����� ������ ���.

#��))� �(��)����

Trap any error by including a corresponding routine within the exception handlingsection of the PL/SQL block.

�,���(

EXCEPTION WHEN exception1 [OR exception2 . . .] THEN statement1; statement2; . . . [WHEN exception3 [OR exception4 . . . THEN statement1; statement2; . . .] [WHEN OTHERS THEN statement1; statement2; . . .]

where: exception is the standard name of a predefined exceptionor the name of a user-defined exceptiondeclared within the declarative section.

WHEN OTHERS indicates the exception handling routine for anyexception is not listed explicitly.

/�������

� Place the WHEN OTHERS clause after all other exception handling clauses.

� You can have at most one WHEN OTHERS clause.

� Begin exception-handling section of the block with the keyword EXCEPTION.

� Define several exception handlers, each with their own set of actions, for theblock.

� When an exception occurs, PL/SQL will process only one handler before leavingthe block.

For more information, seeOracle Course Catalog to attend Develop Applications with Database Procedurescourse.

Page 274: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ���������01

Page 275: OCP - SQL&PL_SQL(Vol3)

����� ������ ���00

#��))� �����&��� ������+ ��� �� �(��)����

Trap a predefined Oracle7 Server error by referencing its standard name within thecorresponding exception-handling routine.

��2)�� �����&��� �(��)����

Exception NameOracle ServerError Number Description

NO_DATA_FOUND ORA-01403 Single row SELECT returned no data.

TOO_MANY_ROWS ORA-01422 Single row SELECT returned morethan one row.

INVALID_CURSOR ORA-01001 Illegal cursor operation occurred.

ZERO_DIVIDE ORA-01476 Attempted to divide by zero.

DUP_VAL_ON_INDEX ORA-00001 Attempted to insert a duplicate valueinto a column that has a unique index.

You can use the debugging capabilities in Procedure Builder to identify and trapexceptions prior to moving procedures to the database.

For more information, seePL/SQL User’s Guide and Reference, Release 2.3 “Predefined Exceptions” section.

Page 276: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ���������0�

Page 277: OCP - SQL&PL_SQL(Vol3)

����� ������ ���0�

#��))� �����&��� ������+ ��� �� �(��)���� ���������

�(�2)��

Eliminate all inventory items for a particular product. Be sure the product number isvalid.

PROCEDURE elim_inventory (v_product_id IN s_product.id%TYPE) IS v_id s_product.id%TYPE;BEGIN SELECT id INTO v_id FROM s_product WHERE id = v_product_id; DELETE FROM s_inventory WHERE product_id = v_product_id; COMMIT;EXCEPTION WHEN NO_DATA_FOUND THEN ROLLBACK; TEXT_IO.PUT_LINE(TO_CHAR(v_product_id)||

’ is invalid.’); WHEN TOO_MANY_ROWS THEN ROLLBACK; TEXT_IO.PUT_LINE(’Data corruption in S_PRODUCT.’); WHEN OTHERS THEN ROLLBACK; TEXT_IO.PUT_LINE(’Other error occurred.’);END elim_inventory;

Only one exception is raised and handled at any time.

Page 278: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ���������0!

0

���� ��� ������� 0 ���� ��� �������������������

� ������ ��� ������������

Page 279: OCP - SQL&PL_SQL(Vol3)

����� ������ ���0�

#��))� 3��������&��� ������+ ��� �� �(��)����

Trap a non-predefined Oracle7 Server error by declaring it first, rather than by usingthe WHEN OTHERS handler. The declared exception will be raised implicitly. Besure to reference the declared exception in the exception handling section.

#��))� � 3��������&��� ������+ ��� �� �(��)���

1. Declare the name for the exception within the declarative section.

�,���(

exception EXCEPTION;

where: exception is the name of the exception.

2. Associate the declared exception with the standard Oracle7 Server error numberusing the pragma EXCEPTION_INIT statement.

�,���(

PRAGMA EXCEPTION_INIT (exception, error_number);

where: exception is the previously-declared exception.

error_number is a standard Oracle7 Server error number.

3. Reference the declared exception within the corresponding exception handlingroutine.

For more information, seeOracle7 Server Messages, Release 7.3.

Page 280: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ���������0*

0

0

���� ��� ������� 0 ������� ���� ���������� �� ���� ���� �!� ���������

� ������ ��� ������������

Page 281: OCP - SQL&PL_SQL(Vol3)

����� ������ ���0+

#��))� �����4�&��� �(��)����

Trap a user-defined exception by declaring it and raising it explicitly.

#��))� � �����4�&��� �(��)���

1. Declare the name for the user-defined exception within the declarative section.

�,���(

exception EXCEPTION;

where: exception is the name of the exception.

2. Raise the exception explicitly within the executable section using the RAISEstatement.

�,���(

RAISE exception;

where: exception is the previously declared exception.

3. Reference the declared exception within the corresponding exception handlingroutine.

Page 282: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ���������0-

Page 283: OCP - SQL&PL_SQL(Vol3)

����� ������ ���0.

����� #��))� 5�������

When an exception is trapped in the WHEN OTHERS section, you can use a set ofgeneric functions for identifying those errors.

6��3 �#��'� �(��)��� �������

The exception-handling section only traps those exceptions specified; any otherexceptions would not be trapped unless you use the WHEN OTHERS exceptionhandler. This will trap any exception not yet handled. For this reason, the WHENOTHERS is be the last exception handler defined.

The WHEN OTHERS handler traps all exceptions not already trapped. Some Oracletools have their own predefined exceptions that you can raise to cause events in theapplication. WHEN OTHERS also traps these exceptions.

5������� &�� ����� #��))�

When an exception occurs, you can identify the associated error code or errormessage by using two functions. Based on the values of the code or message, you candecide what subsequent action to take based upon the error.

Function Description

SQLCODE Returns the numeric value for the error code. You can assign itto a NUMBER variable.

SQLERRM Returns character data containing the message associated withthe error number.

�(�2)�� ���7�4� 8�����

SQLCODE Value Description

0 No exception encountered.

1 User-defined exception.

+100 NO_DATA_FOUND exception.

negative_number Another Oracle7 Server error number.

Truncate the value of SQLERRM to a known length before attempting to write it to avariable.

Page 284: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ����������1

Page 285: OCP - SQL&PL_SQL(Vol3)

����� ������ ����0

���)���� �(��)����

Instead of trapping an exception within the PL/SQL block, propagate the exception toallow the calling environment to handle it. Each calling environment will have itsown way of displaying and accessing errors.

7���� �� ���2��� �(��)��� ������

Calling Environment Exception Handling Capabilities

SQL*Plus Unhandled exception number and message aredisplayed on the screen.

Procedure Builder Unhandled exception number and message aredisplayed on the screen.

Developer/2000 Forms Unhandled exception number and message areaccessible in a trigger by means of theERROR_CODE and ERROR_TEXT packagedfunctions.

Precompiler application Unhandled exception number is accessible throughthe SQLCA data structure.

An enclosing PL/SQL block Unhandled exceptions can be trapped by theexception handling routine of the enclosing block.

���)���� �� �(��)��� � � ��������9

When a sub-block handles an exception, it terminates normally, and control resumesin the enclosing block immediately after the sub-block END statement.

However, if PL/SQL raises an exception and the current block does not have ahandler for that exception, the exception propagates in successive enclosing blocksuntil it finds a handler. If none of these blocks handle the exception, this causes anunhandled exception in the host environment.

When the exception propagates to an enclosing block, the remaining executableactions in that block are bypassed.

One advantage of this behavior is that you can enclose statements that require theirown exclusive error handling in their own block, while leaving more generalexception handling to the enclosing block.

Page 286: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� �����������

Page 287: OCP - SQL&PL_SQL(Vol3)

����� ������ �����

��22��,

Program for exceptions that may arise during the execution of the PL/SQL block.

�(��)��� #,)��

� Predefined Oracle7 Server error.

� Non-predefined Oracle7 Server error.

� User-defined error.

������ �(��)����

� Trap the exception within the PL/SQL block in an exception handling routine.

� Allow the exception to propagate to the calling environment.

���)���� �(��)����

� Propagate an exception through a series of nested blocks.

� Terminate PL/SQL processing with success by handling the exception in anenclosing block.

� Terminate the PL/SQL processing with failure by passing the unhandledexception to the calling environment.

Page 288: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ����������!

Page 289: OCP - SQL&PL_SQL(Vol3)

����� ������ �����

������� � �� �"

In this practice, you create exception handlers for specific situations.

������� 7�������

� Handling named exceptions

� Creating and invoking user-defined exceptions

Page 290: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ����������*

Page 291: OCP - SQL&PL_SQL(Vol3)

����� ������ ����+

������� ��

1. Modify the procedure to handle exceptions. The procedure tries to update regionnumbers for existing departments.

a. Load the LABS\p25q1a.pls script file. Note: The procedure UPDATE_DEPT2is loaded and compiled.

b. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (50,’US’);

c. Write an exception handler for the error to pass a message to the user that thespecified region does not exist.

d. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (31,’Asia’);

e. Write an exception handler for the error to pass a message to the user that thespecified region already has a department of that name.

f. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (99,’Europe’);

g. Write an exception handler for the error to pass a message to the user that thespecified department number does not exist.

Reminder: Use the SQL attribute %NOTFOUND and raise an exceptionmanually.

Page 292: OCP - SQL&PL_SQL(Vol3)

���������� �� ������� ��� ��� ������ ��� ��������� ����������-

������� �� ���������

If you have time, complete the following exercise.

2. Write a procedure named SALARY_RANGE that prints the names of theemployees that make plus or minus $100 of the salary value entered.

a. If there is no employee within that salary range, then print a message to theuser indicating that is the case. Use an exception for this case.

b. If there are more than 3 employees within that range, then the message shouldindicate how many employees have that salary range.

Your results should look like the list below. Results have been formatted to fitthe page.

PL/SQL> SALARY_RANGE (1000);

Employees who make around $1000 are: Biri, Schwartz, Smith

PL/SQL> SALARY_RANGE (900);

4 employee salaries are within $100 of $900

PL/SQL> SALARY_RANGE (2000);

No records within the $2000 range.

Page 293: OCP - SQL&PL_SQL(Vol3)

������� �� ���

Page 294: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ��� ����� �������� ������� ��

Page 295: OCP - SQL&PL_SQL(Vol3)

������� �� ��� ���

�������

PL/SQL (Procedural Language/SQL) is an extension to SQL. It is a language thatallows you to combine multiple SQL statements with procedural controls such asidentifiers, conditional, and iterative constructs in a PL/SQL block.

�������� ���� ���

� Modularize program development by grouping similar concepts together andnesting blocks

� Declare identifiers, for example, variables, constants, and cursors

� Program with procedural language structures, for example, IF statements andloops

� Exception handling for Oracle7 Server errors and user-defined exceptions

� Port code between applications and the Oracle7 Server

� Integrate Oracle7 stored subprograms and application subprograms

� Improve performance by sending a block of code to the server

��� �����

A PL/SQL block contains code in up to four sections. The header section is whereyou set the name and parameters for named blocks. The declarative section isoptional and contains all variables, constants, cursors, and user-defined exceptionsthat will be referenced within the executable section. The executable section isrequired and contains SQL statements to manipulate data in the database and PL/SQLstatements to manipulate data in the block. The exception-handling section is optionaland specifies the actions to perform when errors and abnormal conditions arise withinthe executable section.

�������� ������

Anonymous blocks are unnamed blocks. They are declared at the point in anapplication where they are to be executed and are passed to the PL/SQL engine forexecution at runtime. You can embed an anonymous block within a precompilerprogram and within SQL*Plus or Server Manager. Triggers in Developer/2000components consist of such blocks.

Page 296: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ��� ����� �������� ������� ��!

Page 297: OCP - SQL&PL_SQL(Vol3)

������� �� ��� ��"

������� ���������

���������

Procedures are named PL/SQL blocks that store a series of actions for later execution.The procedure can contain zero or more parameters, which are arguments that you listwhen calling the procedure. Procedures can either be application specific or stored inthe Oracle7 Server.

#��������

A function returns a value to the calling environment. You must declare the RETURNdatatype in the header section of the function definition, and define the value to bereturned in the PL/SQL block. You can also declare a list of parameters to be passedinto the function. Functions are called as part of an expression.

$% �� ���

You can use DML statements in your PL/SQL blocks. Use the SELECT statement toretrieve data from the database.

� The SELECT statement contains an additional mandatory clause: the INTOclause. In the INTO clause, list the output variables for receiving the data. TheSELECT statement must return exactly one row or an error will occur.

� The INSERT statement adds new rows of data to the table.

� The UPDATE statement modifies existing rows in the table.

� The DELETE statement removes unwanted rows from the table.

� COMMIT ends the current transaction by making all pending changes to thedatabase permanent.

� ROLLBACK ends the current transaction by discarding all pending changes.

Page 298: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ��� ����� �������� ������� ���

Page 299: OCP - SQL&PL_SQL(Vol3)

������� �� ��� ��&

������� ���������

�# '���������� ����������

The PL/SQL IF statement is similar to the structure of IF statements in otherprocedural languages. It allows PL/SQL to perform actions selectively based uponconditions. If the controlling Boolean condition is TRUE, the associated sequence ofstatements is executed; if the controlling Boolean condition is FALSE or NULL, theassociated sequence of statements is passed over.

�������(� ��) ����������

You can use one of three loop structures to repeat a sequence of statements.

� The basic loop consists of the body of statements to be repeated enclosed betweenthe delimiters LOOP and END LOOP. This uncontrolled loop is an infinite loopthat is to be avoided. To avoid an infinite loop, add an EXIT statement.

� FOR loops have a control statement at the front of the LOOP keyword todetermine the number of iterations PL/SQL performs.

� The WHILE loop repeats a sequence of statements until the controlling conditionis no longer TRUE. The condition is evaluated at the start of each iteration.

'������

PL/SQL cursors let you name a private SQL area and access its stored information.The cursor directs all phases of processing. Explicit cursors are declared and namedby the programmer and manipulated through specific statements within the block’sexecutable actions. Control explicit cursors in a loop with four steps: declare, open,fetch, and close. Cursor FOR loops are a shortcut to open the cursor, fetch rows oncefor each loop iteration, and automatically close the cursor after all rows areprocessed.

*+��)���� ,�������

An exception is an identifier in PL/SQL, raised during the execution of a block thatterminates its main body of actions. A block will always terminate when PL/SQLraises an exception, but you specify an exception handler to perform final actions.Exceptions can be raised either by the Oracle7 Server or by the user. You can eithertrap an exception in the exception-handling section of the block, or allow it topropagate to the calling environment.

�������� �������

Oracle Procedure Builder is a tool you can use to create, execute, and debug PL/SQLprograms used in your application tools, such as a form or report, or on the Oracle7Server through its graphical interface.

Page 300: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ��� ����� �������� ������� ��-

Page 301: OCP - SQL&PL_SQL(Vol3)

������� �� ��� ��.

������� �(��(��/

This practice has you build a PL/SQL-based application to insert, update, and deleterecords in a video store database and generate a report. The database contains onlythe essential tables.

������� '�������

� Creating procedures and functions

� Inserting, updating, and deleting data

� Incorporating IF statements and loops

� Handling exceptions

Note: If you are new to the class, you can execute the buildvid.sql script inSQL*Plus to create and populate the tables. If you want to drop the work youdid in the course summary from the SQL section, you can execute thedropvid.sql script in SQL*Plus to drop their tables. Then, you can execute thebuildvid.sql script in SQL*Plus to create and populate the tables.

Page 302: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ��� ����� �������� ������� ��01

Page 303: OCP - SQL&PL_SQL(Vol3)

������� �� ��� ��00

������� �

*����� 2��������3�) $������

The facing page contains an entity relationship diagram depicting the tables andcolumns for a small movie rental application.

1. Complete the database design by writing subprograms to perform the followingactions.

a. Create a function named NEW_MEMBER to return the membership numberfor that new member. Be sure to use a sequence generator to create the uniquemember numbers. Check the data dictionary for the sequence name.

b. Create a function named NEW_RENTAL to record a new rental based on amember’s last name. Return a message with the expected due date. If two ormore people have the same last name, store the first name, last name, phone,and membership number for all matching last names in the RESULTS table.

c. Create a procedure named MEM_TITLES to retrieve all the titles rented by amember. Store the results in the RESULTS table.

d. If a title is rented, create a reservation for that movie. Name your procedureRESERVE_MOVIE.

e. When a video is returned, change the rental status for that returned copy.When the video is successfully checked in, store a message in the RESULTStable. Check the to see if there are reservations for the film title, and store amessage in the RESULTS table. Name your procedure RETURN_RENTAL.

f. If a video is returned damaged, change its status to DAMAGED. If that copywas the only copy owned by the store, store a message to buy another copy inthe RESULTS table. If only one copy remains for rental, store a warning thatonly one copy is left for rental in the RESULTS table. Name your procedureDAMAGED_COPY.

g. Create a procedure named TOP_RENTAL to determine the top rental. Allowfor more than one top rental. Store the names and a message of the top rentalsin the RESULTS table.

Page 304: OCP - SQL&PL_SQL(Vol3)

������������ �� ������� �� ��� ��� ����� �������� ������� ��0