54
BD05/06 BD05/06 PL/SQL PL/SQL Introduction Introduction Structure of a block Structure of a block Variables and types Variables and types Accessing the database Accessing the database Control flow Control flow Cursors Cursors Exceptions Exceptions Procedures and functions Procedures and functions

BD05/06 PL/SQL Introduction Structure of a block Variables and types Accessing the database Control flow Cursors Exceptions Procedures

Embed Size (px)

Citation preview

Page 1: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

PL/SQLPL/SQL

IntroductionIntroduction Structure of a blockStructure of a block Variables and typesVariables and types Accessing the databaseAccessing the database Control flowControl flow CursorsCursors ExceptionsExceptions Procedures and functionsProcedures and functions

Page 2: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

IntroductionIntroduction

PL/SQL stands for PL/SQL stands for Procedural Language/SQLProcedural Language/SQL. .

PL/SQLPL/SQL extends SQL extends SQL by adding constructs found in by adding constructs found in procedural languages, resulting in a structural language procedural languages, resulting in a structural language that is more powerful than SQL. that is more powerful than SQL.

The basic unit in PL/SQL is aThe basic unit in PL/SQL is a block block. All PL/SQL . All PL/SQL programs are made up of blocks, which can be nested programs are made up of blocks, which can be nested within each other. Typically, each block performs a within each other. Typically, each block performs a logical action in the program. logical action in the program.

Page 3: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

PL/SQL EnvironmentPL/SQL Environment

Page 4: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

BenefitsBenefits

• IntegrateIntegrate of database technology and of database technology and procedural programming capabilitiesprocedural programming capabilities

Provide improved Provide improved performanceperformance of an of an applicationapplication

• ModularizeModularize program development program development• PortablePortable among host environments among host environments

supporting Oracle server and PL/SQLsupporting Oracle server and PL/SQL Handle Handle errorserrors

Page 5: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Structure of a blockStructure of a block

DECLAREDECLARE        

/* Declarative section: variables, types, cursors, /* Declarative section: variables, types, cursors, user-defined exceptions */  user-defined exceptions */  

BEGINBEGIN        

/* Executable section: procedural and SQL statements /* Executable section: procedural and SQL statements go here. */    go here. */    

/* This is the only section of the block that is /* This is the only section of the block that is required. */     required. */    

EXCEPTIONEXCEPTION        

/* Exception handling section: error handling /* Exception handling section: error handling statements go here. */    statements go here. */    

ENDEND; /* mandatory */; /* mandatory */

Page 6: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Block (1)Block (1) The only SQL statements The only SQL statements allowedallowed in a in a

PL/SQL program are PL/SQL program are SELECT, INSERT, SELECT, INSERT, UPDATE, DELETEUPDATE, DELETE and several other data and several other data manipulation statements plus some manipulation statements plus some transaction control. transaction control.

Data definition statements like CREATE, Data definition statements like CREATE, DROP, or ALTER are DROP, or ALTER are not allowednot allowed..

The The executableexecutable section also contains section also contains constructs such as assignments, constructs such as assignments, branches, loops, procedure calls, and branches, loops, procedure calls, and triggerstriggers

Page 7: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Block (2)Block (2) PL/SQL is PL/SQL is not case sensitivenot case sensitive. C style . C style

commentscomments (/* ... */) may be used. (/* ... */) may be used.

To To execute a PL/SQL programexecute a PL/SQL program, we must , we must follow the program text itself by: a line with follow the program text itself by: a line with a single dot (a single dot (".""."), and then a line with ), and then a line with “run”“run”; ; or a line with or a line with “/”“/”

We can invoke a PL/SQL program either We can invoke a PL/SQL program either by typing it in sqlplus or by putting the by typing it in sqlplus or by putting the code in a file and invoking the file code in a file and invoking the file

Page 8: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Variables and Types (1)Variables and Types (1)

Information is transmitted between a Information is transmitted between a PL/SQL program and the database PL/SQL program and the database through through variablesvariables. .

Every variable has a specific Every variable has a specific typetype associated with it, that can be:associated with it, that can be: One of the types used by SQL for database One of the types used by SQL for database

columns columns A generic type used in PL/SQL such as A generic type used in PL/SQL such as

NUMBER NUMBER Declared to be the same as the type of some Declared to be the same as the type of some

database column database column

Page 9: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Variables and Types (2)Variables and Types (2)

The most commonly used generic type is The most commonly used generic type is NUMBERNUMBER. Variables of type NUMBER can . Variables of type NUMBER can hold either an integer or a real number. hold either an integer or a real number.

The most commonly used character string The most commonly used character string type is type is VARCHAR(VARCHAR(nn),), where where nn is the is the maximum length of the string in bytes. maximum length of the string in bytes. This length is required, and there is no This length is required, and there is no default. default.

Page 10: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

DECLARE DECLARE       

price  NUMBER;price  NUMBER;

     myBeer VARCHAR(20); myBeer VARCHAR(20);

Page 11: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Declaring Boolean variablesDeclaring Boolean variables

Only the values Only the values TRUE, FALSE, and NULLTRUE, FALSE, and NULL can be assigned to a Boolean variable.can be assigned to a Boolean variable.

• • The variables are compared by the logicalThe variables are compared by the logical

operators AND, OR, and NOT.operators AND, OR, and NOT.

• • The variables always yield TRUE, FALSE, The variables always yield TRUE, FALSE, or NULL.or NULL.

• • Arithmetic, character, and date Arithmetic, character, and date expressions can be used to return a expressions can be used to return a Boolean value.Boolean value.

Page 12: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

DECLAREDECLARE

v_flag v_flag BOOLEANBOOLEAN := := FALSEFALSE;;

BEGINBEGIN

v_flag := v_flag := TRUETRUE;;

ENDEND;;

Page 13: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

The The %TYPE%TYPE attribute attribute

A PL/SQL variable can be used to A PL/SQL variable can be used to manipulate data manipulate data stored in a existing relation. stored in a existing relation.

The variable must have the same type as the relation The variable must have the same type as the relation column. If there is any type mismatch, variable column. If there is any type mismatch, variable assignments and comparisons may not work the way assignments and comparisons may not work the way you expect. you expect.

To be safe, instead of hard coding the type of a variable, To be safe, instead of hard coding the type of a variable, you should use the you should use the %TYPE%TYPE operator. operator.

Ex:Ex:DECLAREDECLARE     myBeer Beers.name%TYPE;     myBeer Beers.name%TYPE;

gives PL/SQL variable myBeer whatever type was gives PL/SQL variable myBeer whatever type was declared for the name column in relation Beers. declared for the name column in relation Beers.

Page 14: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

The The %ROWTYPE%ROWTYPE attribute attribute

A variable may also have a type that is a A variable may also have a type that is a record with record with several fieldsseveral fields. .

The simplest way to declare such a variable is to use The simplest way to declare such a variable is to use %ROWTYPE%ROWTYPE on a relation name. The result is a record on a relation name. The result is a record type in which the fields have the same names and types type in which the fields have the same names and types as the attributes of the relation. as the attributes of the relation.

Ex:Ex:DECLAREDECLARE     beerTuple Beers%ROWTYPE;     beerTuple Beers%ROWTYPE;

makes variable beerTuple be a record with fields name makes variable beerTuple be a record with fields name and manufacture, assuming that the relation has the and manufacture, assuming that the relation has the schema Beers(name, manufacture). schema Beers(name, manufacture).

Page 15: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Default values and Default values and assignmentsassignments

The initial value of any variable, regardless of its type, is The initial value of any variable, regardless of its type, is NULLNULL. .

We can assign values to variables, using the We can assign values to variables, using the ":="":=" operator. operator. The assignment can occur either immediately after the type The assignment can occur either immediately after the type

of the variable is declared, or anywhere in the executable of the variable is declared, or anywhere in the executable portion of the program. portion of the program.

Ex:Ex:DECLAREDECLARE         a a NUMBERNUMBER := 3; := 3; BEGINBEGIN         a := a + 1;a := a + 1;

ENDEND; ; . . runrun; ;

Page 16: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Bind variablesBind variables

Variable that you declare in a Variable that you declare in a host host environment (ex: SQL*Plus)environment (ex: SQL*Plus), used to pass , used to pass run-time values (number or characters) run-time values (number or characters) into or out of PL/SQL programsinto or out of PL/SQL programs

The only kind that may be printed with a The only kind that may be printed with a printprint command. command.

Bind variables must be Bind variables must be prefixed with a prefixed with a coloncolon in PL/SQL statements in PL/SQL statements

Page 17: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Steps to create a bind Steps to create a bind variablevariable

1.1. We declare a bind variable as follows:We declare a bind variable as follows:VARIABLEVARIABLE <name> <type> <name> <type>where the type can be only one of three where the type can be only one of three things: NUMBER, CHAR, or CHAR(things: NUMBER, CHAR, or CHAR(nn). ).

2.2. We may then assign to the variable in a We may then assign to the variable in a following PL/SQL statement, but we must following PL/SQL statement, but we must prefix it with a colon. prefix it with a colon.

3.3. Finally, we can execute a statement :Finally, we can execute a statement :        PRINTPRINT :<name>; :<name>; outside the PL/SQL statement outside the PL/SQL statement

Page 18: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

VARIABLEVARIABLE

x x NUMBERNUMBER          

BEGINBEGIN                

      :x := 1;      :x := 1;     

ENDEND;    ;    

..

run;    run;    

PRINTPRINT :x; :x;

Page 19: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

DBMS_OUTPUT.PUT_LINEDBMS_OUTPUT.PUT_LINEpackagepackage

An An Oracle-supplied packaged procedureOracle-supplied packaged procedure An alternative for displaying data from a PL/SQL blockAn alternative for displaying data from a PL/SQL block Must be enabled in SQL*Plus Must be enabled in SQL*Plus with: with: SET SERVEROUTPUT ONSET SERVEROUTPUT ON

Page 20: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Simple programs accessing the Simple programs accessing the databasedatabase

The simplest form of program has some The simplest form of program has some declarations followed by an declarations followed by an executable sectionexecutable section consisting of one or more of the SQL statements consisting of one or more of the SQL statements with which we are familiar. with which we are familiar.

After the SELECT clause, we must have an After the SELECT clause, we must have an INTO INTO clauseclause listing variables, one for each attribute in the listing variables, one for each attribute in the SELECT clause, into which the components of the SELECT clause, into which the components of the retrieved tuple must be placed. retrieved tuple must be placed.

The SELECT statement in PL/SQL only works if the The SELECT statement in PL/SQL only works if the result of the query contains a single tupleresult of the query contains a single tuple. If the . If the query returns more than one tuple, you need to use query returns more than one tuple, you need to use a cursora cursor

Page 21: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Example (SQL)Example (SQL)

CREATE TABLECREATE TABLE T1(     T1(    

e e INTEGERINTEGER,     ,    

f f INTEGERINTEGER ); );

DELETE FROMDELETE FROM T1; T1;

INSERT INTOINSERT INTO T1 T1 VALUESVALUES(1, 3); (1, 3);

INSERT INTOINSERT INTO T1 T1 VALUES(VALUES(22, 4); , 4);

Page 22: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Example (PL/SQL)Example (PL/SQL)

DECLAREDECLARE        

a a NUMBERNUMBER;   ;   

    b b NUMBERNUMBER;;

BEGINBEGIN        

SELECTSELECT e,f e,f INTOINTO a,b a,b FROMFROM T1 T1 WHEREWHERE e>1;     e>1;    

INSERT INTOINSERT INTO T1 T1 VALUESVALUES(b,a); (b,a);

ENDEND;;

..

runrun; ;

Page 23: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Control flowControl flow PL/SQL allows you to branch and create loops in a fairly PL/SQL allows you to branch and create loops in a fairly

familiar way. familiar way. An An IF statementIF statement looks like: looks like:

IFIF <condition> <condition> THENTHEN <statement_list> <statement_list>ELSEELSE <statement_list> <statement_list>END IFEND IF;;

The The ELSEELSE part is optional. If you want a multiway branch, part is optional. If you want a multiway branch, use:use:

IFIF <condition_1> <condition_1> THENTHEN ... ... ELSIFELSIF <condition_2> <condition_2> THENTHEN ... ... ... ... ... ...ELSIFELSIF <condition_n> <condition_n> THENTHEN ... ... ELSEELSE ... ... END IFEND IF; ;

Page 24: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

DECLAREDECLARE         a a NUMBERNUMBER; ;   b b NUMBERNUMBER; ; BEGINBEGIN        

SELECTSELECT e,f e,f INTOINTO a,b a,b FROMFROM T1 T1 WHEREWHERE e>1;     e>1;     IFIF b=1 b=1 THENTHEN      

        INSERT INTOINSERT INTO T1 T1 VALUES VALUES (b,a);  (b,a);        ELSEELSE                

INSERT INTOINSERT INTO T1 T1 VALUESVALUES (b+10,a+10);    (b+10,a+10);       END IFEND IF; ; ENDEND; ; ..runrun; ;

Page 25: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

LoopsLoops

Loops are created with the following: Loops are created with the following: LOOPLOOP         <loop_body> /* A list of <loop_body> /* A list of statements. */ statements. */

END LOOP;END LOOP;

At least one of the statements in At least one of the statements in <loop_body> should be an EXIT statement <loop_body> should be an EXIT statement of the formof the form

EXIT WHENEXIT WHEN <condition>; <condition>;

The loop breaks if <condition> is true. The loop breaks if <condition> is true.

Page 26: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

DECLAREDECLARE          i i NUMBERNUMBER := 1; := 1;BEGIN BEGIN       LOOP        LOOP        

INSERT INTOINSERT INTO T1 T1 VALUESVALUES (i,i);   (i,i);           i := i+1;        i := i+1;         EXIT WHENEXIT WHEN i>100;     i>100;     END LOOP; END LOOP; END;END; ..run;run;

Page 27: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Other useful loop-forming Other useful loop-forming statements statements

A WHILE loop can be formed with:  A WHILE loop can be formed with:      WHILEWHILE <condition> <condition> LOOPLOOP                

<loop_body>     <loop_body>     END LOOP;END LOOP;

A simple FOR loop can be formed with:  A simple FOR loop can be formed with:        FORFOR <var> <var> ININ <start>..<finish> <start>..<finish> LOOPLOOP                 <loop_body>     <loop_body>    

END LOOP;END LOOP; Here, <var> can be any variable; it is local to the for-loop and Here, <var> can be any variable; it is local to the for-loop and

need not be declared. Also, <start> and <finish> are need not be declared. Also, <start> and <finish> are constants.constants.

Page 28: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

CursorsCursors

A A cursorcursor is a variable that runs through the is a variable that runs through the tuples of some relation. tuples of some relation. Can be a stored table or the answer to some Can be a stored table or the answer to some

query. query. By By fetchingfetching into the cursor each tuple of into the cursor each tuple of

the relation, we can write a program to the relation, we can write a program to read and process the value of each such read and process the value of each such tuple.tuple.

If the relation is stored, we can also If the relation is stored, we can also update or deleteupdate or delete the tuple at the current the tuple at the current cursor position. cursor position.

Page 29: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Example (1)Example (1)

Uses T1(e,f) whose tuples are pairs of Uses T1(e,f) whose tuples are pairs of integers.integers.

The program will delete every tuple whose The program will delete every tuple whose first component is less than the second, first component is less than the second, and insert the reverse tuple into T1. and insert the reverse tuple into T1.

Page 30: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Example (2)Example (2)DECLAREDECLARE                

/* Output variables to hold the result of the query: */  /* Output variables to hold the result of the query: */            a T1.ea T1.e%TYPE%TYPE;  ;            b T1.fb T1.f%TYPE%TYPE;         ;        

/* Cursor declaration: */  /* Cursor declaration: */            CURSORCURSOR T1Cursor T1Cursor IS  IS                    SELECTSELECT e, f e, f FROMFROM T1 T1 WHEREWHERE e < f   e < f            FOR UPDATEFOR UPDATE;  ;  BEGIN BEGIN         OPENOPEN T1Cursor; T1Cursor;         LOOPLOOP  /* Retrieve each row of the result of the above query  /* Retrieve each row of the result of the above query

 into PL/SQL variables: */  into PL/SQL variables: */                 FETCHFETCH T1Cursor T1Cursor INTOINTO a, b;           a, b;          

/* If there are no more rows to fetch, exit the loop: *//* If there are no more rows to fetch, exit the loop: */                EXIT WHENEXIT WHEN T1Cursor T1Cursor%NOTFOUND%NOTFOUND;           ;            /* Delete the current tuple: *//* Delete the current tuple: */                DELETE FROMDELETE FROM T1 T1 WHERE CURRENT OFWHERE CURRENT OF T1Cursor;            T1Cursor;            /* Insert the reverse tuple: */ /* Insert the reverse tuple: */                 INSERT INTOINSERT INTO T1 T1 VALUESVALUES(b, a);(b, a);          END LOOP;END LOOP;             /* Free cursor used by the query. *//* Free cursor used by the query. */        CLOSECLOSE T1Cursor; T1Cursor; END; END;

Page 31: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExceptionsExceptions

An An exceptionexception is an identifier in PL/SQL is an identifier in PL/SQL that is raised during execution.that is raised during execution.

• • How is it How is it raisedraised??

– – An Oracle error occurs.An Oracle error occurs.

– – You raise it explicitly.You raise it explicitly.

• • How do you How do you handlehandle it? it?

– – Trap it with a handler.Trap it with a handler.

– – Propagate it to the calling environment.Propagate it to the calling environment.

Page 32: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Handling exceptionsHandling exceptions

Page 33: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Exception types Exception types

Page 34: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Trapping exceptionsTrapping exceptionsSyntax:Syntax:

EXCEPTIONEXCEPTIONWHENWHEN exception1 exception1 [[OROR exception2 exception2 . . .] . . .] THENTHEN

statement1statement1; /* one or more PL/SQL or ; /* one or more PL/SQL or SQL statements */SQL statements */

statement2statement2;;. . .. . .

[[WHENWHEN exception3 exception3 [[OROR exception4 exception4 . . .] . . .] THENTHENstatement1statement1;;statement2statement2;;. . .]. . .]

[[WHEN OTHERS THENWHEN OTHERS THENstatement1statement1;;statement2statement2;;. . .]. . .]

Only one handler is processedOnly one handler is processed WHEN OTHERS is unique and must be the last handlerWHEN OTHERS is unique and must be the last handler

Page 35: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Trapping pre-defined Oracle Trapping pre-defined Oracle server errorsserver errors

Reference the standard name in the Reference the standard name in the exception handling routine.exception handling routine.

• • Sample predefined exceptions:Sample predefined exceptions:

– – NO_DATA_FOUNDNO_DATA_FOUND

– – TOO_MANY_ROWSTOO_MANY_ROWS

– – INVALID_CURSORINVALID_CURSOR

– – ZERO_DIVIDEZERO_DIVIDE

– – DUP_VAL_ON_INDEXDUP_VAL_ON_INDEX

Page 36: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Functions for Trapping Functions for Trapping ExceptionsExceptions

When an exception occurs, you can identify the associated When an exception occurs, you can identify the associated error code or error messageerror code or error message by using two functions. by using two functions.

Based on the values of the code or message, you can Based on the values of the code or message, you can decide which subsequent action to take based on the error.decide which subsequent action to take based on the error.– SQLCODESQLCODE: Returns the numeric value for the error code: Returns the numeric value for the error code– SQLERRMSQLERRM: Returns the message associated with the : Returns the message associated with the

error numbererror number Examples of SQLCODE values:Examples of SQLCODE values:

0: no exception encountered0: no exception encountered 1: user-defined exception1: user-defined exception +100: NO_DATA_FOUND_EXCEPTION+100: NO_DATA_FOUND_EXCEPTION Negative number: another Oracle server error numberNegative number: another Oracle server error number

Page 37: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

Page 38: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Trapping Nonpredefined OracleTrapping Nonpredefined OracleServer ErrorsServer Errors

Page 39: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

Page 40: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Trapping User-Defined Trapping User-Defined ExceptionsExceptions

Page 41: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

Page 42: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Propagating exceptionsPropagating exceptions

Page 43: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

RAISE_APPLICATION_ERRORRAISE_APPLICATION_ERRORProcedureProcedure

Syntax:Syntax:raise_application_error raise_application_error ((error_number,error_number,messagemessage[, {TRUE | FALSE}]);[, {TRUE | FALSE}]);

• • You can use this procedure to issue user-error You can use this procedure to issue user-error messages from stored subprograms.messages from stored subprograms.

• • You can report errors to your application and avoid You can report errors to your application and avoid returning unhandled exceptions.returning unhandled exceptions.

Used in two different places:Used in two different places:– – Executable sectionExecutable section– – Exception sectionException section

• • Returns error conditions to the user in a manner Returns error conditions to the user in a manner consistent with other Oracle server errorsconsistent with other Oracle server errors

Page 44: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

Page 45: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Procedures (1)Procedures (1) Behave very much like procedures in other Behave very much like procedures in other

programming language programming language A procedure is introduced by the keywords A procedure is introduced by the keywords

CREATE PROCEDURECREATE PROCEDURE followed by the followed by the procedure name and its parameters. procedure name and its parameters.

CREATE may be followed by CREATE may be followed by OR OR REPLACEREPLACE. . If the procedure is already created, we will not If the procedure is already created, we will not

get an errorget an error If the previous definition is a different procedure If the previous definition is a different procedure

with the same name, the old procedure will be with the same name, the old procedure will be lost. lost.

Page 46: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Procedures(2)Procedures(2) Can have any number of parameters, each followed by a Can have any number of parameters, each followed by a modemode and a type. The possible modes are: and a type. The possible modes are:

IINN (read-only), (read-only), OUTOUT (write-only), and (write-only), and INOUTINOUT (read+write). (read+write). The type specifier in a parameter declaration must be The type specifier in a parameter declaration must be

unconstrainedunconstrained• CHAR(10) and VARCHAR(20) are illegal; CHAR(10) and VARCHAR(20) are illegal; CHARCHAR or or

VARCHARVARCHAR should be used instead. The actual length of should be used instead. The actual length of a parameter depends on the corresponding argument a parameter depends on the corresponding argument that is passed in when the procedure is invoked. that is passed in when the procedure is invoked.

Following the arguments is the keyword Following the arguments is the keyword ASAS (IS is a (IS is a synonym). Then comes the body, which is essentially a synonym). Then comes the body, which is essentially a PL/SQL block. PL/SQL block.

The DECLARE section should The DECLARE section should not startnot start with the keyword with the keyword DECLAREDECLARE. Rather, following AS we have: . Rather, following AS we have:

... AS <local_var_declarations>... AS <local_var_declarations>BEGINBEGIN

<procedure_body><procedure_body>END; /END; /

Page 47: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExample

Addtuple1:Addtuple1: given an integer i, inserts the tuple (i, 'xxx') into the given an integer i, inserts the tuple (i, 'xxx') into the following example relation: following example relation:

CREATE TABLECREATE TABLE T2 (a T2 (a INTEGERINTEGER,     b ,     b CHAR(10)CHAR(10) ); );

CREATE PROCEDURECREATE PROCEDURE addtuple1(i addtuple1(i IN NUMBERIN NUMBER) ) ASAS BEGIN     BEGIN    

INSERT INTOINSERT INTO T2 T2 VALUESVALUES(i, 'xxx'); (i, 'xxx'); END; END;

. . run; run;

Page 48: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Executing proceduresExecuting procedures The “The “runrun”” at the end runs the statement that at the end runs the statement that createscreates the the

procedure; it does not execute the procedure. procedure; it does not execute the procedure. To execute the procedure, use another PL/SQL To execute the procedure, use another PL/SQL

statement, in which the procedure is invoked as an statement, in which the procedure is invoked as an executable statement. executable statement.

Ex: Ex: BEGINBEGIN

addtuple1(99); addtuple1(99); ENDEND; /; /

Or invoke the “execute” commandOr invoke the “execute” commandEx: Ex: EXECUTE EXECUTE addtuple1(99); addtuple1(99);

Page 49: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Another exampleAnother example

CREATE PROCEDURECREATE PROCEDURE addtuple2( x T2.a addtuple2( x T2.a%TYPE%TYPE, y , y T2.bT2.b%TYPE%TYPE) ) AS AS

BEGIN     BEGIN     INSERT INTOINSERT INTO T2(a, b) T2(a, b) VALUESVALUES(x, y); (x, y);

END; END; . . run;run; /* to add a tuple (10, 'abc') to T2 *//* to add a tuple (10, 'abc') to T2 */BEGIN BEGIN         addtuple2(10, 'abc'); addtuple2(10, 'abc');

END; . run;END; . run;

Page 50: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

OUT and INOUT parametersOUT and INOUT parameters

Assigning values to parameters declared Assigning values to parameters declared as as OUT or INOUTOUT or INOUT causes the causes the corresponding input arguments to be corresponding input arguments to be written. written.

Because of this, the input argument for an Because of this, the input argument for an OUT or INOUT parameter should be OUT or INOUT parameter should be something with an "lvalue”.something with an "lvalue”.

A A constant or a literal argumentconstant or a literal argument should should not be passed in for an OUT/INOUT not be passed in for an OUT/INOUT parameter. parameter.

Page 51: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ExampleExampleCREATE TABLECREATE TABLE T3 (a T3 (a INTEGERINTEGER, b , b INTEGERINTEGER ); );

CREATE PROCEDURECREATE PROCEDURE addtuple3(a addtuple3(a NUMBERNUMBER, b , b OUT OUT NUMBERNUMBER) ) ASAS

BEGIN  BEGIN       b := 4;  b := 4;  

    INSERT INTOINSERT INTO T3 T3 VALUESVALUES(a, b); (a, b); END; END; . run; . run;

DECLARE DECLARE        v v NUMBERNUMBER;;BEGIN  BEGIN       addtuple3(10, v); addtuple3(10, v); END; . run; END; . run;

Page 52: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Procedures and FunctionsProcedures and Functions We can also write functions instead of procedures. In a function We can also write functions instead of procedures. In a function

declaration, we follow the parameter list by RETURN and the declaration, we follow the parameter list by RETURN and the type of the return value: type of the return value:

CREATE FUNCTIONCREATE FUNCTION <func_name>(<param_list>) <func_name>(<param_list>) RETURNRETURN <return_type> <return_type> ASAS ... ...

In the body of the function definition, "RETURN <expression>;" In the body of the function definition, "RETURN <expression>;" exits from the function and returns the value of <expression>. exits from the function and returns the value of <expression>.

To find out what procedures and functions you have created, To find out what procedures and functions you have created, use the following SQL query: use the following SQL query:

selectselect object_type, object_name object_type, object_name fromfrom user_objectsuser_objects wherewhere object_type = 'PROCEDURE' or object_type object_type = 'PROCEDURE' or object_type = 'FUNCTION'; = 'FUNCTION';

To drop a stored procedure/function: To drop a stored procedure/function: drop procedure <procedure_name>; drop procedure <procedure_name>; drop function <function_name>; drop function <function_name>;

Page 53: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

Discovering errorsDiscovering errors PL/SQL does not always tell you about PL/SQL does not always tell you about

compilation errors. Instead, it gives you a compilation errors. Instead, it gives you a cryptic message such as "procedure cryptic message such as "procedure created with compilation errors". If you created with compilation errors". If you don't see what is wrong, try issuing the don't see what is wrong, try issuing the command:command:

show errors procedureshow errors procedure <procedure_name>;<procedure_name>;

Alternatively, you can type:Alternatively, you can type: SHO ERRSHO ERR (short for SHOW ERRORS)(short for SHOW ERRORS) to see the most recent compilation error. to see the most recent compilation error.

Page 54: BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures

BD05/06BD05/06

ReferencesReferences

Notes from Univ. Of Stanford: “Using Notes from Univ. Of Stanford: “Using Oracle PL/SQL”,Oracle PL/SQL”,http://www-db.stanford.edu/~ullman/fcdb/oracle/or-plsql.htmlhttp://www-db.stanford.edu/~ullman/fcdb/oracle/or-plsql.html

““Oracle 9i: Program with PL/SQL”, Instructor Guide, Oracle 9i: Program with PL/SQL”, Instructor Guide, Volume 1, ORACLEVolume 1, ORACLE