Oracle Part3

download Oracle Part3

of 106

Embed Size (px)

Transcript of Oracle Part3

  • 7/29/2019 Oracle Part3


    Chapter 4:

    Introduction to PL/SQL

    Guide to Oracle 10g

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 2

    Lesson A Objectives

    After completing this lesson, you should be able to:

    Describe the fundamentals of the PL/SQL

    programming language Write and execute PL/SQL programs in SQL*Plus

    Execute PL/SQL data type conversion functions

    Display output through PL/SQL programs

    Manipulate character strings in PL/SQL programs

    Debug PL/SQL programs

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 3


    DB users use GUI applications to enter data intoinput boxes, and then click buttons to executeprograms that perform DB functions.

    We will use the following utilities:Form builder

    Report builder

    To use these utilities effectively an understanding ofPL/SQL is needed.

    PL/SQL is a procedural programming language thatOracle utilities use to manipulate DB data.

    Programming or scripting language conceptsunderstanding is necessary.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 4

    Fundamentals of PL/SQL

    PL/SQL program combines SQL queries withprocedural commands (if/then, loops).

    It is a full-featured programming language Executed using Oracle 10gutilities such as:SQL*Plus or

    Forms Builder It is an interpreted language

    Its commands are not a case sensitive. Inside single

    quotes are case sensitive.. M != m Semicolon ends each command

    It contains reserved words and built in functions.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 5

    PL/SQL Command Capitalization


  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 6

    PL/SQL Variables and Data Types

    Variable names must follow the Oracle namingstandard

    Strongly typed language:Explicitly declare each variable including data type

    before using variable

    Variable declaration syntax: var i abl e_name dat a_t ype_decl ar at i on;

    Default value always NULL PL/SQL supports: scalar, composite, reference and


  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 7

    Scalar Variables

    Reference single value Data types correspond to Oracle 10gdatabase data





  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 8

    General Scalar Data Types

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 9

    Composite Variables

    Data Structure is a data object made up of multiple

    individual data elements Composite variable is a data structure contains

    multiple scalar variables




  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 10

    Reference Variables

    Reference variables directly reference specificdatabase column or row

    Reference variables assume data type of associatedcolumn or row

    %TYPE data declaration syntax: var i abl e_namet abl ename. f i el dname%TYPE;

    %ROWTYPE data declaration syntax: var i abl e_name t abl ename%ROWTYPE;

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 11

    Reference Variables

    The (%TYPE) reference data type specifies avariable that references a single DB field.

    current_f_last FACULTY.F_LAST%TYPE;

    The current_f_last variable assumes a data type ofVARCHAR2(30), because this is the data type ofthe f_last column in the FACULTY table.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 12

    Reference Variables

    The (%ROWTYPE) reference data type createscomposite variables that reference the entire data

    record. Facul t y_r ow FACULTY%ROWTYPE;

    The variable faculty_row references all of thecolumns in the FACULTY table, and each column

    has the same data type as its associated DB column.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 13

    LOB Data Types

    It declares variables that referencebinary orcharacterdata objects up to 4 GB.

    LOB values in PL/SQL programs must be

    manipulated using special package calledDBMS_LOB.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 14

    PL/SQL Program Blocks

    Declaration section (DECLARE) Optional (variable declaration)

    Execution section (BEGIN) Required (Program statements)

    Exception section (EXCEPTION) Optional (Error handling statements)

    Comment statements

    Enclosed within /* and */ Two hyphens (--) for a single line comment


  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 15

    PL/SQL Arithmetic Operators in

    Describing Order of Precedence

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 16

    Assignment Statements

    Assigns value to variable Operator


    Syntax var i abl e_name : = val ue;

    String literal must be enclosed in a singlequotation marks.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 17

    Assignment Statements You can use the := in the declaration section to

    give initial values. s_id NUMBER := 100;

    You can use DEFAULT instead: s_id NUMBER DEFAULT 100;

    IfNULL value is used in an assignment statementwith arithmetic operation, the result is always


  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 18

    Executing a PL/SQL Program in


    Create and execute PL/SQL program blockswithin variety of Oracle 10gdevelopmentenvironments:

    SQL *PlusForm Builder

    Report Builder

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 19

    Displaying PL/SQL Program Output in SQL*Plus

    PL/SQL outputbuffer

    Memory area on database server

    Stores programs output values before they aredisplayed to user

    Buffer size should be increased before output is

    displayed: SET SERVEROUTPUT ON SI ZE buf f er _si ze

    Default buffer size

    2000 bytes

    If the output is more than buffer_size, error apperas.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 20

    Displaying PL/SQL Program Output in SQL*Plus


    Display program output

    DBMS_OUTPUT. PUT_LI NE( ' di spl ay_t ext' ) ;

    Display maximum of 255 characters of text data.

    More than 255 characters gives an error.

    Example: s_name := Ahmed Mahmoud;

    DBMS_OUTPUT. PUT_LI NE( s_name) ;

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 21

    Writing a PL/SQL Program

    Write PL/SQL program in Notepad or another texteditor

    Copy and paste program commands into SQL*Plus

    Press Enter after last program command Type front slash ( / ) (to instruct the interpreter to execute the code)

    Then press Enter again

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 22

    Writing a PL/SQL Program


    Good programming practicePlace DECLARE, BEGIN, and END commandsflush with left edge of text editor window

    Indent commands within each section

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 23

    PL/SQL Program Commands

    Output: Todays data is

    18-OCT-07PL/SQL procedure successfully completed

    If no output appears use: SQL> set serveroutput on

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 24

    PL/SQL Data Conversion Functions

    Implicit data conversions Interpreter automatically converts value from one data

    type to another(the command DBMS_OUTPUT.PUT_LINE(todays_date), theinterpreter automatically converted the todas_date DATE variable to a text string foroutput

    ). If PL/SQL interpreter unable to implicitly convert value

    error occurs

    Explicit data conversionsConvert variables to different data typesUsing built in data conversion functions

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 25

    PL/SQL Data Conversion Functions of


  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 26

    Manipulating Character Strings with

    PL/SQL String

    Character data value

    Consists of one or more characters


    Joining two separate strings Parse

    Separate single string consisting of two data items

    separated by commas or spaces Built in functions to concatenate and parse strings

    in SQL*Plus are as follows:

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 27

    Concatenating Character Strings

    Double bar Operator



    new_st r i ng : = st r i ng1 | | st r i ng2;

    Exampl e: Ful l _name : = Qusai | | | | Abuei n

    You must conver t NUMBER and DATE dat at ype var i abl es ( TO_CHAR) i nt o a st r i ngbef or e concat enat i ng i t .

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 28

    Removing Blank Leading and Trailing

    Spaces from Strings

    LTRIM functionRemove blank leading spaces

    st r i ng : = LTRI M( st r i ng_var i abl e_name) ;

    RTRIM functionRemove blank trailing spaces

    st r i ng : = RTRI M( st r i ng_var i abl e_name) ;

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 29

    Finding the Length of Character


    LENGTH function syntax

    st r i ng_l engt h : = LENGTH( st r i ng_var i abl e_name) ;

    Space i s i ncl uded wher ever i t appear s. DBMS_OUTPUT. PUT_LI NE( LENGTH( ' Today' ' s dat e i s ' ) ) ;

    Gi ves 20.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 30

    Character String Case Functions

    Modify case of character strings Functions and syntax:

    st r i ng : =

    UPPER( st r i ng_var i abl e_name) ; st r i ng : =

    LOWER( st r i ng_var i abl e_name) ;

    st r i ng : =I NI TCAP( st r i ng_var i abl e_name) ;

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 31

    Parsing Character Strings


    Searches string for specific substring

    If substring is found, the starting position of itwithin the original_string is returned as integervalue. Otherwise, zero is returned.

    Syntax: st ar t _posi t i on : =

    I NSTR( or i gi nal _st r i ng, subst r i ng) ;

    st ar t _posi t i oi n shoul d be i nt egerdat a t ype.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 32

    Parsing Character Strings

    SUBSTRfunctionExtracts specific number of characters from characterstring starting at given point

    Syntax: ext r act ed_st r i ng : = SUBSTR( st r i ng_var i abl e,

    st ar t i ng_poi nt, number _of _char act er s) ;

    To parse a string, usually INSTR is used to find delimiter and then use theSUBSTR.

    Example page 206, 207.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 33

    Debugging PL/SQL Programs

    Syntax errorOccurs when command does not follow guidelinesof programming language

    Generate compiler or interpreter error messages Logic error

    Does not stop program from running

    Results in incorrect result

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 34

    Program with a Syntax Error

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 35

    Program with a Logic Error

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 36

    Finding Syntax Errors

    Often involve:Misspelling reserved word

    Omitting required character in command

    Using built-in function improperly Interpreter

    Flags line number and character location of syntaxerrors

    May actually be on preceding line

    Displays error code and message

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 37

    Finding Syntax Errors (continued)

    Comment out program linesTo find error

    Cascading errors are called so when

    One syntax error can generate many more errorsFix the first error andrerun the program. Do not fix

    next errors before rerunning the program.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 38

    Finding Logic Errors

    Caused by:

    Not using proper order of operations in arithmeticfunctions

    Passing incorrect parameter values to built-infunctions

    Creating loops that do not terminate properly

    Using data values that are out of range or not ofright data type

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 39

    Finding Logic Errors (continued)


    Program that enables software developers to pauseprogram execution and examine current variable

    valuesBest way to find logic errors

    SQL*Plus environment does not provide PL/SQL

    debuggerUse DBMS_OUTPUT to print variable values

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 40

    Lesson A Summary

    PL/SQL data types:




    Program block



  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 41

    Lesson B Objectives

    After completing this lesson, you should be able to:

    Create PL/SQL decision control structures Use SQL queries in PL/SQL programs

    Create loops in PL/SQL programs Create PL/SQL tables and tables of records

    Use cursors to retrieve database data into PL/SQLprograms

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 42

    Lesson B Objectives (continued)

    Use the exception section to handle run-time errors inPL/SQL programs

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 43

    PL/SQL Decision Control Structures


    Processes statements one after another

    Decision control structures

    Alter order in which statements executeBased on values of certain variables

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 44


    Syntax:I F condi t i onTHEN

    commands t hat execut e i f condi t i oni s TRUE;

    END I F;


    Expression evaluates to TRUE or FALSE If TRUE commands execute


  • 7/29/2019 Oracle Part3



    Guide to Oracle 10g 45

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 46

    PL/SQL Comparison Operators

    Do not get confused with the equal (=) sign and the assignment (:=) operator

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 47



    I F condi t i onTHEN

    commands t hat execut e i f condi t i oni s TRUE;


    commands t hat execut e i f condi t i oni s FALSE;

    END I F; Evaluates ELSE command if condition FALSE

  • 7/29/2019 Oracle Part3



    Guide to Oracle 10g 48

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 49

    Nested IF/THEN/ELSE

    Placing one or more IF/THEN/ELSE statementswithin program statements that execute after IF orELSE command

    Important to properly indent program lines

    IF/ELSIF Syntax:

  • 7/29/2019 Oracle Part3



    Syntax:I F condi t i on1 THEN

    commands t hat execut e i f condi t i on1 i s TRUE;

    ELSI F condi t i on2THEN

    commands t hat execut e i f condi t i on2 i s TRUE;

    . . .


    commands t hat execut e i f no condi t i ons TRUE;

    END I F;

    Not e t her e i s no E f i r e I F i n ELSI F, and no spaces.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 51

    Logical Operators AND, OR, and


    Create complex expressions for decision controlstructure condition


    Expressions on both sides of operator must be truefor combined expression to be TRUE


    Expressions on either side of operator must be truefor combined expression to be TRUE

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 52

    Logical Operators AND, OR, and

    NOT (continued)

    Order of evaluation:

    NOT (evaluated first)



  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 53

    Evaluating AND and OR in an


  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 54

    Using SQL Queries in PL/SQL Programs

    Use SQL action query

    Put query or command in PL/SQL program

    Use same syntax as execute query or command inSQL*Plus

    Can use variables instead of literal values to specify

    data values

    Ex: curr_f_name := Ahmad

    We need to insert Ahmad into a column S_FIRST

    INSERT INTO student (s_first)

    VALUES (curr_f_name);

    Ex: WHERE s_first = curr_f_name;

    PL/SQL Command

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 55

    Using SQL Commands in PL/SQL


  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 56


    Systematically executes program statements

    Periodically evaluates exit condition to determine

    if loop should repeat or exit Pretest loop

    Evaluates exit condition before any programcommands execute

    Posttest loop

    Executes program commands before loop evaluatesexit condition for first time

    In PL/SQL there are FIVE loop structures.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 57

    The LOOP...EXIT Loop This kind of loop can be either Pretest or posttest

    Syntax:LOOP[ pr ogr am st at ement s]

    I F condi t i onTHENEXI T;

    END I F;

    [ addi t i onal pr ogr am st at ement s]END LOOP;

    The LOOP EXIT Loop

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10 58

    The LOOP...EXIT Loop LOOP keyword signals the beginning of the loop.

    If the IF/THEN decision structure is the first code in theloop, it is a pretest loop.

    If the IF/THEN decision structure is the last code in the

    loop, it is a posttest loop.

    The LOOP...EXIT WHEN Loop

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 59

    p Can be either a Pretest or posttest



    pr ogr am st at ement s

    EXI T WHEN condi t i on;END LOOP;

    The WHILE...LOOP

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 60

    It is a Pretest loop that test the condition before it executeany program statements.


    WHI LE condi t i on LOOP

    pr ogr am st at ement sEND LOOP;

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 61

    The Numeric FOR Loop

    In the previous LOOP structures we had toincrement the counter variable.

    The numeric FOR does not require explicitcounter increment

    Automatically increments counter

    Syntax:FOR count er _var i abl e I N st ar t _val ue . . . end_val ue


    pr ogr am st at ement s


    Start_value and end_value must be integer. The increment is always done

    by 1.

  • 7/29/2019 Oracle Part3



    Guide to Oracle 10g 62

    C FOR L

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 63

    Cursors FOR Loop

    Pointer to memory location on database server thatthe DBMS uses to process a SQL query

    A cursor is a mechanism by which you can assign

    a name to a "select statement" and manipulate theinformation within that SQL statement

    Use to:

    Retrieve and manipulate database data from thetables into PL/SQL programs

    Types: Implicit


    Implicit Cursors

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 64

    For every SQL statement execution certain area inmemory is allocated. PL/SQL allow you to name thisarea. This private SQL area is calledcontext area or

    cursor. A cursor acts as a handle orpointerinto thecontext area. A PL/SQL program controls the contextarea using the cursor.

    Context area Is a memory location on the DB server contains

    information about query, such as the number of rowsthe query processed.


  • 7/29/2019 Oracle Part3


    Implicit Cursors

    Active setSet of data rows that query retrieves using


    Implicit cursor Is a Pointer to the context area.

    Called so because you do not need explicitcommand to create it.

    Guide to Oracle 10g 65


  • 7/29/2019 Oracle Part3


    For SQL queries returning single row PL/SQL

    declares implicit cursors. Implicit cursors are simple SELECT statements

    and are written in the BEGIN block (executablesection) of the PL/SQL.

    Implicit cursors are easy to code, and they retrieve

    exactly one row. PL/SQL implicitly declares cursors for all DML


    The most commonly raised exceptions here areNO_DATA_FOUND orTOO_MANY_ROWS.

    Guide to Oracle 10g 66To be discussed later

    Implicit Cursors (continued)

  • 7/29/2019 Oracle Part3


    Implicit Cursors (continued)

    Can be used to assign output of SELECT query toPL/SQL program variables:

    When query will return only one record

    If the query returns more than one record or zerorecords, an error occurs.


    SELECT ename, sal INTO ena, esa FROM EMP WHERE EMPNO = 7844;

  • 7/29/2019 Oracle Part3



    Implicit Cursors (continued)

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 69

    Implicit Cursors (continued)

    Syntax:SELECT f i el d1, f i el d2, . . .

    I NTO var i abl e1, var i abl e2, . . .

    FROM t abl e1, t abl e2, . . .WHERE j oi n_condi t i ons

    AND sear ch_condi t i on_t o_r et r i eve_1_r ecor d;

    The val ue of f i el d1 i s assi gned t o var i abl e1, f i el d2t o var i abl e2 and so on.

    Dat a t ypes of f i el d1, f i el d2 and var i abl e1, var i abl e2must be t he same.

    After we discuss join

    Implicit Cursors (continued)

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 70

    Implicit Cursors (continued)

    Useful to use %TYPE reference data type To declare variables used with implicit cursors

    Syntax: var_name tablename.fieldname%TYPE

    Ex: curr_f_last faculty.f_last%TYPE Error ORA-01422: exact fetch returns more than requested

    number of rows .

    Implicit cursor query tried to retrieve multiple records Error ORA-014032: no data found.

    If one of these errors occur, you shouldmodify the query to

    retrieve only one record, oruse Explicit cursor.

  • 7/29/2019 Oracle Part3


  • 7/29/2019 Oracle Part3



    Guide to Oracle 10g 72

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 73

    Explicit Cursors

    Retrieve and display data in PL/SQL programs for

    query that might:Retrieve multiple records

    Return no records at all

    Steps for creating and using explicit cursorDeclare cursor

    Open cursorFetch data rows

    Close cursor

  • 7/29/2019 Oracle Part3


    Explicit cursor functions

    Guide to Oracle 10g 74

  • 7/29/2019 Oracle Part3


    Controlling Explicit Cursors

    Guide to Oracle 10g 75

  • 7/29/2019 Oracle Part3



    Guide to Oracle 10g 76

    Explicit Cursors (continued)

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 77

    Explicit Cursors (continued)

    Declare explicit cursor syntax: by declaring an explicit cursor, you create amemory location on the DB server that processes a query and stores the retrieved records .

    Syntax:CURSOR cur sor _name I S sel ect _quer y; cur sor _name: Any val i d PL/ SQL name.

    sel ect _quer y: The quer y t hat r et r i eves t he dat a val ues.

    Open explicit cursor syntax: by doing so the interpreter checks for syntaxerror, upon correct it translate the query into machine-language format. The system thencreates the memory location that stores the active set (contains the retrieved data using

    SELECT) .Syntax

    OPEN cur sor _name;

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 78

    Explicit Cursors (continued)

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 79

    p ( )

    Fetchcommand is used to retrieve the data from the DB into the active set, one row

    at a time.

    Because a query might return several rows, you execute theFETCH command within a (LOOPEXIT WHEN) loop:



    FETCH cur sor _name I NTO

    var i abl e_name( s) ;

    EXI T WHEN cur sor _name%NOTFOUND;

    Cursor_name is name of the cursor defined previously.

    Variable_name(s) represents either a single variable or a list of variables that receivesdata from the cursors SELECT query. (every retrieved column from the DB table isassociated with a program variable, %TYPE or %ROWTYPE)

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 80

    Explicit Cursors (continued)

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 81

    p ( )

    Active set pointeris created when processing explicitcursor that:

    Indicates memory location of the next record retrievedfrom database

    After the last record of the query is executed, that

    pointer points to an empty record.The condition (EXI T WHEN cur sor _name%NOTFOUND)

    guarantees the exit when the pointer points to an empty


    Explicit Cursors (continued)

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 82

    Explicit Cursors (continued)

    Close cursor syntax:

    CLOSE cur sor _name;

    You shoul d cl ose a cur sor af t erpr ocessi ng al l r ecor ds so as t he memor y

    and ot her r esour ces ar e avai l abl e t ot he syst em f or ot her t asks.

    The syst em aut omat i cal l y cl oses t hecur sor when t he pr ogr am ends, i f youf or get t o do so.

    Processing Explicit Cursors Using a

  • 7/29/2019 Oracle Part3



    Often used to process explicit cursors that retrieveand display database records

    Use %TYPE variable to display explicit cursorvalues (See example Figure 4-29 page 243)

    Use %ROWTYPE variable to display explicit

    cursor values

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 84

    Processing Explicit Cursors Using a

    Cursor FOR Loop

    Make it easier than LOOP...EXIT WHEN to processexplicit cursors.

    For Loop automatically:

    Opens cursorFetches records

    Closes cursor

    Processing Explicit Cursors Using a

    C FOR L ( i d)

  • 7/29/2019 Oracle Part3



    Cursor FOR Loop (continued)

    Syntax:FOR var i abl e_name( s) I N cur sor _name


    pr ocessi ng commands


    Explicit Cursors Using a Cursor FOR Loop

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 86

    Explicit Cursors Using a Cursor FOR Loop,


    The cur sor var i abl e can be r ef er encedout si de t he Loop Exi t When. Whi l e cannot be r ef er enced out si de t he For Loop.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 87

    Handling Runtime Errors in PL/SQL


    Pl/SQL supports Exception handling, that is:

    Programmers place commands for displaying error messagesand

    Give users options for fixing errors in programs exception

    section (Optional section in a PL/SQL program block. Page 195) Runtime errors

    Cause program to fail during execution

    Exception section is used to handle runtime error. Unwanted event.

  • 7/29/2019 Oracle Part3


    Handling Runtime Errors in PL/SQL Programs (cont )

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 89

    Handling Runtime Errors in PL/SQL Programs (cont.)

    An exception orunwantedevent is raisedwhen aruntime error occurs.

    The control is transferred to the exception section,where the exception handlerhas the following options:Correct error without notifying user of problem

    Inform user of error without taking corrective actionCorrect and inform

    Inform the user and allow him to decide what action to

    take. After exception handler executesProgram ends

    Handling Runtime Errors in PL/SQL Programs (cont )

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 90

    Handling Runtime Errors in PL/SQL Programs (cont.)

    There are three kinds of exceptions:


    UndefinedUser defined

    Predefined Exceptions

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 91


    Most common errors that occur in programs PL/SQL language:

    Assigns exception name

    Provides built-in exception handlerfor each predefinedexception

    System automatically displays error message informinguser of the nature of the problem

    One can create exception handlers to display alternate

    error messages for predefined exception

    C PL/SQL P d fi d

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 92

    Common PL/SQL Predefined


    Exception Handler Syntax

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 93

    Exception Handler Syntax

    The syntax to write an alternate error messages for predefined handler.

    Exception Handler Syntax

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 94

    Exception Handler Syntax

    exception_name1, exception_name2, refer to thename of the predefined exception (table 4-10).

    Exception handler commandsrepresent commandsthat display the error message.

    WHEN OTHERS THEN clause is a handler

    presents a general message to describe errors that donot have specific exception handlers.

  • 7/29/2019 Oracle Part3



    Exception Handler Syntax

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 96

    When using alternate error message, such as in the example 4-

    35, which handles only the NO_DATA_FOUND. Anunanticipated error might occur. That way no handler exists tohandle such unanticipated errors.

    For that reason it is helpful to use the WHEN OTHERSexception handler too, so as to display messages for thatsituation.

    To do this, use SQLERRMbuilt-in function (SQL ERRorMessage).

    That function returns a string that contains the most recent error

    code and its description. First define a varchar2 variable of length 512 to assign it the

    error message: error_message := SQLERRM;

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 97

    Undefined Exceptions

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 98


    Less common errors

    Do not have predefined names

    One must explicitly declare exception in programsdeclaration section and

    Associate the new exception with a specific Oracle

    error code then

    Create an exception handler in the exception section

    Using the same syntax as for predefined exceptions

    Syntax of Undefined Exceptions

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 99


    e-exception_name EXCEPTION;

    PRAGMA EXCEPTION INIT(e-exception_name, -Oracle_error_code);

    e-exception_name represents name you assign to theexception.

    PRAGMA EXCEPTION INIT: a command associates your

    exception name with a specific Oracle error code. The hyphen (-) must precede the Oracle_error_code. See for

    example Figure 4-37 next slide, the code is2291.

    See example Figure 4-38 on undefined exception, next slide.

  • 7/29/2019 Oracle Part3



    User-defined Exceptions

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 101

    User-defined exceptions do not raise Oracle runtimeerror. BUT

    Require exception handling to:

    Enforce business rules (special rules of a company,example page 253. Rule: one can only delete grades withvaluesNULL. Other grades can notbe deleted. If a user

    tries to delete a grade that its value is not NULL, theprogram should raise an exception and display a message)or

    Ensure the integrity of database

    General Syntax for Declaring, Raising, and

    H dli U d fi d E i

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 102

    Handling a User-defined Exception

    General Syntax for Declaring, Raising, and Handling a User-

    defined Exception

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 103

    de ed cept o

    To raise the exception, you must use the IF/THEN,which evaluates the exception condition (grade IS NOT


    If the condition is TRUE, the RAISE command isexecuted and raises the exception (transfer execution to

    the exception section). The exception handler executes anddisplays the error-

    handling messages.

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 104

  • 7/29/2019 Oracle Part3


    Guide to Oracle 10g 105

    Lesson B Summary

    Decision control structures:



    IF/ELSIF Loop

    Repeats action multiple times until it reaches exit


    Five types of loops

  • 7/29/2019 Oracle Part3


    Lesson B Summary (continued)


    Pointer to memory location that DBMS uses toprocess SQL query

    Types: Implicit


    Exception handlingThree exception types