itbis373 database development

115
1 ITBIS373 Database Development Lecture 2 – Chapter 4B Introduction to PL/SQL

Upload: chi

Post on 15-Jan-2016

41 views

Category:

Documents


1 download

DESCRIPTION

ITBIS373 Database Development. Lecture 2 – Chapter 4B Introduction to PL/SQL. Objectives. 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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: ITBIS373 Database Development

1

ITBIS373 Database Development

Lecture 2 – Chapter 4B Introduction to PL/SQL

Page 2: ITBIS373 Database Development

2

Objectives

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/SQL

programs Use the exception section to handle errors in

PL/SQL programs

Page 3: ITBIS373 Database Development

3

PL/SQL Decision Control Structures

So far the programs we have written use sequential processing, this is one statement after the other

Most programs do require decision control structures that will alter the order the statements execute in based on the values of certain variables

In PL/SQL you can create the following decision control structures: IF/THEN IF/THEN/ELSE IF/ELSIF

Page 4: ITBIS373 Database Development

4

IF/THEN The PL/SQL IF/THEN decision control structure has the following

syntax: IF condition THEN

commands that execute if condition is TRUE; END IF;

The condition is an expression that PL/SQL has to be able to evaluate as either TRUE or FALSE

The condition can compare two values such as a variable and a literal or the condition can be a Boolean variable

The PL/SQL comparison operators are shown on the next slide

Page 5: ITBIS373 Database Development

5

IF/THEN

Page 6: ITBIS373 Database Development

6

IF/THEN If the condition evaluates as TRUE one or more program

statements execute If the condition evaluates as FALSE or NULL the program skips

the statements It is good practice to format IF/THEN structures by indenting the

program statements that execute if the condition is TRUE so the structure is easier to read, same applies to FALSE

If the condition evaluates as NULL it behaves the same as if the condition evaluated as FALSE

Can evaluate to NULL if a variable has not been assigned a value, of is of the variables in the condition have a NULL value

Page 7: ITBIS373 Database Development

7

IF/THEN

The above PL/SQL script shows no output since this was not done on a Friday, notice SERVEROUTPUT is set to ON, so this is not the problem

Page 8: ITBIS373 Database Development

8

IF/THEN

The above PL/SQL script shows output since it was modified with the != to reverse the logic

Page 9: ITBIS373 Database Development

9

IF/THEN/ELSE The previous example suggests the need for a decision control

structure that executes alternate program statements when the condition executes as FALSE

This is where the IF/THEN/ELSE structure is used The IF/THEN/ELSE structure has the following syntax:

IF condition THEN

commands that execute if condition is TRUE;

ELSE

commands that execute if condition is FALSE;

END IF;

Page 10: ITBIS373 Database Development

10

IF/THEN/ELSE

The above PL/SQL script shows output since it was modified with the to display output regardless if the condition is TRUE or FALSE

Page 11: ITBIS373 Database Development

11

You can nest IF/THEN/ELSE structures by placing more than one IF/THEN/ELSE statements within the program that execute after the IF or the ELSE command

It is good coding to properly indent code to understand the logic of of the command and to spot syntax errors

The code will be modified again to show the nested IF/THEN/ELSE

Nested IF/THEN/ELSE

Page 12: ITBIS373 Database Development

12

Nested IF/THEN/ELSE

The above PL/SQL script shows output using a nested IF/THEN/ELSE statement, notice the two END IF statements one for each IF

Page 13: ITBIS373 Database Development

13

IF/ELSIF The IF/ELSIF allows you to test for many different conditions,

note spelling of ELSIF The syntax for the IF/ELSIF structure is:

IF condition1 THEN commands that execute if condition1 is TRUE;

ELSIF condition2 THEN commands that execute if condition2 is TRUE; ELSIF condition3 THEN commands that execute if condition3 is TRUE;

... ELSE

commands that execute if none of the conditions are TRUE;

END IF;

Page 14: ITBIS373 Database Development

14

In the IF/ELSIF decision control structure, the interpreter evaluates the condition1, if it is TRUE the interpreter executes the associated program statement(s), then exists the IF/ELSIF structure

If condition1 is FALSE then the interpreter evaluates condition2, it will then evaluate condition2 to determine it is TRUE or FALSE

This continues through the IF/ELSIF structure in a similar fashion as mentioned for condition1

IF/ELSIF

Page 15: ITBIS373 Database Development

15

IF/ELSIF

The above PL/SQL script shows output using the IF/ELSIF statement, notice the single END IF statement and the ELSE to catch an invalid day

Page 16: ITBIS373 Database Development

16

Logical Operators AND, OR and NOT

The AND, OR and the NOT logical operators can be used in to create complex expressions for a decision control structure condition

Each of the individual expression’s TRUE and FALSE values will be combined into a single TRUE or FALSE result for the entire condition

The rules for AND and OR operators are identical to any other use of these in any programming language

Also be aware of which operator is evaluated first if both the AND and OR operators are used

Page 17: ITBIS373 Database Development

17

Logical Operators AND, OR and NOT

The above PL/SQL script shows incorrect output, the current weather is cloudy, yet it is Sunday and the output says it is sunny????

Page 18: ITBIS373 Database Development

18

Complex Conditions

Created with logical operators AND, OR and NOT AND is evaluated before OR, is this statement correct? Use () to set precedence, evaluate the day first then weather

Page 19: ITBIS373 Database Development

19

Logical Operators AND, OR and NOT

The above PL/SQL script shows correct output, the current weather is cloudy, so it is Sunday and the output says it is cloudy

Page 20: ITBIS373 Database Development

20

Category Purpose Example of Command

Can be Used in PL/SQL

Data Definition Language (DDL)

Change the database structure

CREATE, ALTER, DROP

No

Data Manipulation Language (DML)

Queries or Manipulates the data in table

SELECT, INSERT, UPDATE, DELETE

Yes

Transaction Control commands

Organize DML commands into logical transactions

COMMIT, ROLLBACK, SAVEPOINT

Yes

Using SQL Queries in PL/SQL Programs

Page 21: ITBIS373 Database Development

21

Using SQL Queries in PL/SQL Programs

To use a SQL query or DML command or a transaction control command in a PL/SQL command you simply put the query or command in the PL/SQL program using the same syntax you would use to execute the command in SQL*Plus

In PL/SQL you can use variables instead of literal values to specify data values

Page 22: ITBIS373 Database Development

22

For example you could code the following:INSERT INTO student (s_first)VALUES (v_curr_first_name);

You could also perform the following:WHERE s_first = v_curr_first_name;

The value would have to assigned to the variable names that are used above first before they can be used

Next we will write a program that uses DML and transaction control commands to insert records into a table called TERM

Using SQL Queries in PL/SQL Programs

Page 23: ITBIS373 Database Development

23

Start with the SQL*Plus and run the script file provided called emptynorthwoods.sql

This will create the required tables for the Northwoods University database

The tables will be empty, check to verify the TERM table is indeed empty

Using SQL Queries in PL/SQL Programs

Page 24: ITBIS373 Database Development

24

Download Student Data Files

Use the browser to go to www.course.com, select Databases from list on left frame

Page 25: ITBIS373 Database Development

25

Download Student Data Files

Select Oracle in the centre area

Page 26: ITBIS373 Database Development

26

Download Student Data Files

Find the textbook for our course, and select that title

Page 27: ITBIS373 Database Development

27

Download Student Data Files

Select Download Student Files at the bottom of the screen

Page 28: ITBIS373 Database Development

28

Download Student Data Files

Select the link for Data Files for Students

Page 29: ITBIS373 Database Development

29

Download Student Data Files

Select Open to allow you to unzip the file to your hard drive

Page 30: ITBIS373 Database Development

30

Download Student Data Files

I choose to place mine in the same directory I had set up to store my PL/SQL work

Page 31: ITBIS373 Database Development

31

Download Student Data Files

It will place each chapter into its own folder

Page 32: ITBIS373 Database Development

32

Download Student Data Files

We need chapter 4 for the script that is needed for execution, EmptyNorthwoods.sql

Page 33: ITBIS373 Database Development

33

Using SQL Queries in PL/SQL Programs

Run the emptynorthwoods script that is provide in the student data files for this textbook

Page 34: ITBIS373 Database Development

34

Using SQL Queries in PL/SQL Programs

Check to see if the TERM table exists and that it is empty

Page 35: ITBIS373 Database Development

35

Using SQL Queries in PL/SQL Programs

Write the above PL/SQL program in Notepad and execute in SQL*Plus

Page 36: ITBIS373 Database Development

36

Using SQL Queries in PL/SQL Programs

Use a SELECT statement on the TERM table to see if the records exist

Page 37: ITBIS373 Database Development

37

Loops in PL/SQL

Five different types of loops in PL/SQL LOOP … EXIT LOOP … EXIT WHEN WHILE … LOOP Numeric FOR Loops Cursor FOR Loops (look at later in chapter)

Page 38: ITBIS373 Database Development

38

Loops in PL/SQL

Loops can be classified as either a pretest loop or a posttest loop

If the program statements might never be executed use the pretest loop

If the program statements are always executed at least once use the posttest loop

Page 39: ITBIS373 Database Development

39

Loops

To illustrate the different types of loops a table is to be created called COUNT_TABLE

We will use the various types of loops to insert the numbers 1 through 5 into the table, into a column called COUNTER

Page 40: ITBIS373 Database Development

40

Loops

Create table to demonstrate the various types of loops, records will be added and then deleted for each of the various loop types

Page 41: ITBIS373 Database Development

41

The LOOP … EXIT Loop The basic syntax of the command:

LOOP program statements for loop IF condition THEN EXIT; END IF; more program statements for loopEND LOOP;

Loop can either be a pretest or a posttest loop where the condition is tested either before or after the program statements are executed

Page 42: ITBIS373 Database Development

42

The LOOP … EXIT Loop

If the IF/THEN decision structure is the first code in the loop it is then a pretest loop

If the IF/THEN is the last code in the loop it is a posttest loop Good programming practice to indent the program lines between

the LOOP and END LOOP commands to make the loop structure easier to read

Next we will write a PL/SQL program to insert records into the COUNT_TABLE using the LOOP … EXIT loop

Page 43: ITBIS373 Database Development

43

The LOOP … EXIT Loop

Use the LOOP … EXIT loop to insert the 5 records to the table, then verify to see if they are there

Page 44: ITBIS373 Database Development

44

The LOOP … EXIT WHEN Loop

The basic format of the command could look like this:

LOOP

program statements

EXIT WHEN condition;

END LOOP; This loop executes the program statements then tests for the

condition This is a posttest loop the program statements are always

executed at least once and tested after they have executed

Page 45: ITBIS373 Database Development

45

The LOOP … EXIT WHEN Loop

The basic format of the command can also appear as this:

LOOP

EXIT WHEN condition;

program statements

END LOOP; This loop executes the program statements then tests for the

condition This is a pretest loop the program statements are always

executed after the condition is tested

Page 46: ITBIS373 Database Development

46

The LOOP … EXIT WHEN Loop

Use the LOOP … EXIT WHEN loop is used as a posttest loop to insert the five rows to the table, table records were first deleted

Page 47: ITBIS373 Database Development

47

The WHILE … LOOP

The basic format of the command:WHILE condition

LOOP

program statements

END LOOP; This a pretest loop, the condition is evaluated before

any program statements are executed

Page 48: ITBIS373 Database Development

48

The WHILE … LOOP

Table records were first deleted, then the WHLE … LOOP was executed to insert the five records to the table

Page 49: ITBIS373 Database Development

49

The Numeric FOR Loop The basic syntax for the command is:

FOR counter variable IN start value .. end valueLOOP program statementsEND LOOP;

Start and End values must be integers Do not have to declare a counter or increment the counter

manually Counter is defined in the start and end numbers in the FOR

statement and automatically increments each time the loop repeats

DECLARE section is omitted because there is nothing to declare

Page 50: ITBIS373 Database Development

50

The Numeric FOR Loop

Table records were first deleted, then the FOR … LOOP was executed to insert the five records to the table

Page 51: ITBIS373 Database Development

51

Cursors

A pointer is a link to a physical location that stores data In Oracle9i a cursor is a pointer to a memory location on the

database server that the DBMS uses to process a SQL query You use cursors to retrieve and manipulate database data in

PL/SQL programs There are two kinds of cursors implicit and explicit We will now look at how cursors are used to retrieve database

data values into PL/SQL programs

Page 52: ITBIS373 Database Development

52

Implicit Cursors When Oracle processes a SQL INSERT, UPDATE, DELETE or

SELECT command it allocates a memory location on the database server know as the context area

This memory location contains information about the query, such as the number of rows processed by the query, a parsed (machine language) representation of the query

In the case of a SELECT statement that returns data, the active set which is the set of data rows returned by the query

Page 53: ITBIS373 Database Development

53

Implicit Cursors A implicit cursor is a pointer to the context area, which is a

variable that contains the address of the memory location that contains the SQL command’s context area

There are two kinds of cursors, implicit and explicit The implicit cursor is created automatically within the Oracle

environment, and does not need to be declared in the DECLARE section and does not require any code to be written to create it or retrieve its values

The figure on the next slide shows an implicit cursor that points to the context area for a query that retrieves the first record from a table

Page 54: ITBIS373 Database Development

54

Implicit Cursors

Page 55: ITBIS373 Database Development

55

You can use when you want to assign the output of a SELECT query to a PL/SQL variable and you are sure the query will return one and only one record

If none or more than one are returned you will receive an error message

Implicit Cursors

Page 56: ITBIS373 Database Development

56

Implicit Cursor The implicit cursor has the following format:

SELECT field1, field2, …INTO variable1, variable2, …FROM table1, table2, …WHERE search_condition_to_retrieve_1_record;

The receiving variables in the INTO section must be of the same data types as the returned fields and must be declared in the DECLARE section

field1 is assigned to variable1, and field2 to variable2, etc. It is useful to use the %TYPE referential data type, this

guarantees that the declared variable will have the same data type as the table

Page 57: ITBIS373 Database Development

57

Implicit Cursor

To proceed now we need tables that contain data Use the scripts in your data disk for Northwoods to create and

populate the tables with records You can also do the same for Clearwater and Software Experts Use SQL*Plus as we did before with the EmptyNorthwoods.sql

script to execute the three script files included in the Chapter 4 folder, 4Northwoods,sql, 4Clearwater.sql and 4Software.sql

Page 58: ITBIS373 Database Development

58

Implicit Cursor

Implicit cursor used to retrieve the faculty information from the FACULTY table

Page 59: ITBIS373 Database Development

59

Implicit Cursor

Implicit cursor used to retrieve the faculty information from the FACULTY table, returns more than one row, ORA-01422 error code, rewrite to return single row only

Page 60: ITBIS373 Database Development

60Implicit cursor used to retrieve the faculty information from the FACULTY table, value being retrieved does not exist so generates ORA-01403

Implicit Cursor

Page 61: ITBIS373 Database Development

61

Explicit Cursor Explicit Cursors must be used with SELECT statements that

might retrieve a variable number of records or no records Declared in the DECLARE section and processed in the program

body The steps for using an explicit cursor are as follows:

Declare the cursor Open the cursor Fetch the cursor results into PL/SQL variables Close the cursor

Page 62: ITBIS373 Database Development

62

Explicit Cursor Explicit Cursors must be used with SELECT statements that

might retrieve a variable number of records or no records Declared in the DECLARE section and processed in the program

body The steps for using an explicit cursor are as follows:

Declare the cursor Open the cursor Fetch the cursor results into PL/SQL variables Close the cursor

Page 63: ITBIS373 Database Development

63

Explicit Cursor Declaring the explicit cursor names the cursor and defines the query

associated with the cursor The general format is:

CURSOR cursor name IS SELECT query; The cursor name can be any valid PL/SQL variable name The SELECT query is any legal SQL SELECT statement, is the query

that will retrieve the desired data values You may use any valid SQL SELECT statement including queries that

involve set operators, queries with subqueries or nested subqueries The query search condition can contain PL/SQL variables, as long as

the variables are declared before the cursor is declared, and assigned values before the cursor is processed

Page 64: ITBIS373 Database Development

64

Declaring an Explicit Cursor

Example of a declaration for a cursor:DECLARE

current_bldg_code VARCHAR2(5);

CURSOR location_cursor IS

SELECT room

FROM location

WHERE bldg_code = current_bldg_code; You declare a variable then the cursor

Page 65: ITBIS373 Database Development

65

Opening an Explicit Cursor Opening the cursor allows the SQL compiler to parse the SQL

query At this point the individual components are checked for syntax

errors The parsed query is then stored in the context area and creates

memory area for the active set The OPEN command causes the CURSOR to identify the data

rows that satisfy the SELECT but the rows are not actually retrieved as of yet

The general format to open an explicit cursor is:OPEN cursor name;OPEN location_cursor;

Page 66: ITBIS373 Database Development

66

Fetching the Data Rows The FETCH command retrieves the query data from the

database into the active set one row at a time Since the query can return many rows the FETCH is executed in

a loop The general format is as follows:

LOOP FETCH cursor_name INTO variable_name(s);EXIT WHEN cursor_name%NOTFOUND;

The record variable is either a single variable or a list of variables that will receive data

Usually, this variable is declared using one of the reference types that are declared using either %TYPE or %ROWTYPE

Page 67: ITBIS373 Database Development

67

Fetching the Data Rows

Example one:DECLARE CURSOR location_cursor IS SELECT capacity FROM location; room_capacity location.capacity%TYPE;BEGIN OPEN location_cursor; FETCH location_cursor INTO room_capacity; additional processing statementsEND;

Page 68: ITBIS373 Database Development

68

Fetching the Data Rows

Using the %TYPE for processing in an explicit cursor

Page 69: ITBIS373 Database Development

69

Fetching the Data Rows

Example two:DECLARE CURSOR location_cursor IS SELECT bldg_code, room, capacity FROM location; location_row location_cursor%ROWTYPE;BEGIN OPEN location_cursor; FETCH location_cursor INTO location_row; additional processing statementsEND;

Page 70: ITBIS373 Database Development

70

Fetching the Data Rows

Using the %ROWTYPE for processing in an explicit cursor

Page 71: ITBIS373 Database Development

71

Fetching the Data Rows Recall that the %TYPE data type assumes the same data type

as a specific database table field and is declared using the format:

tablename.fieldname%TYPE If a cursor returns multiple fields the output is fetched into a

variable declared using the %ROWTYPE data type The %ROWTYPE can also assume the same data types as the

data fields that a cursor returns when it is declared using the format

row variable name cursor name%ROWTYPE

Page 72: ITBIS373 Database Development

72

Fetching the Data Rows

The individual fields in a row variable can be referenced using the format:

row variable name.database field name For example to access the database field value

returned for bldg_code variable in the cursor you would use the following:

location_row.bldg_code

Page 73: ITBIS373 Database Development

73

Closing a Cursor

A cursor should be closed after processing is completed This frees up memory area and resources so these can be made

available to the system for other tasks The general format for the CLOSE command is:

CLOSE cursor name; In the event you forget to close the cursor it will automatically

close when the program where the cursor is declared ends

Page 74: ITBIS373 Database Development

74

Processing Explicit Cursors Explicit cursors can be processed using a loop that terminates when all

rows have been processed Two different structures can be used the LOOP … EXIT WHEN and the

FOR loop Format for the LOOP … EXIT WHEN

BEGIN OPEN cursor name LOOP FETCH cursor name INTO variables;

EXIT WHEN cursor name%NOTFOUND additional statements END LOOP; CLOSE cursor name;END;

Page 75: ITBIS373 Database Development

75

Explicit Cursor Using LOOP … EXIT WHEN

The previous program script has been changed to reflect the retrieval of several values form a table

A %ROWTYPE variable is being used to store the fetched values from the table

In the program code the individual fields within the row are referenced using the syntax:

row_variable_name.table_fieldname

Page 76: ITBIS373 Database Development

76

Explicit Cursor Using a FOR LOOP

An easier way to process explicit cursors is to use the cursor FOR loop

With this loop you do not need to explicitly OPEN, FETCH the rows or CLOSE the cursor

By using the cursor FOR loop Oracle implicitly does these operations

You cannot reference the cursor values outside of the cursor FOR loop, the syntax is as follows:

FOR cursor_variables IN cursor_name LOOP additional processing statementsEND LOOP;

Page 77: ITBIS373 Database Development

77

Explicit Cursor Using a FOR LOOP

Using the FOR LOOP for processing in an explicit cursor

Page 78: ITBIS373 Database Development

78

Other Explicit Cursor Attributes

During the processing of the EXIT … WHEN loop for explicit cursor, the %NOTFOUND was used to terminate the loop and end processing of retrieved data

Explicit cursors have attributes that describe the cursor’s state Is the cursor open? Were records found or not? How many records were fetched?

Page 79: ITBIS373 Database Development

79

Other Explicit Cursor Attributes

Attribute Description

%NOTFOUND Evaluates as true when the cursor has no rows left to fetch, false when there are rows

%FOUND True when the cursor has rows to fetch and false when the cursor has no rows to fetch

%ROWCOUNT Returns the number of rows the cursor has fetched so far

%ISOPEN Returns true if the cursor is open and false if the cursor is closed

Page 80: ITBIS373 Database Development

80

CURSOR Attributes

The %ISOPEN attribute can be used before or after the cursor is opened

The other attributes can only be used while the cursor is open The %NOTFOUND was used previously in the LOOP … EXIT

WHEN processing structure to exit the loop when all cursor rows were fetched and processed

The %NOTFOUND and %FOUND attributes are also useful for detecting when a cursor returns no rows, this is shown on the next slide

Page 81: ITBIS373 Database Development

81

Handling Runtime Errors is PL/SQL Programs

Programmers can’t do much if the network fails or the user’s computer crashes

Programmers should do everything possible to prevent incorrect data from being entered or to notify the user of errors

PL/SQL offers exception handling, the error codes and solutions to user problems are coded in the EXCEPTION section of the program

Page 82: ITBIS373 Database Development

82

Errors can occur at two different points in a program:

At compile time At run time

Compile errors are usually spelling, or syntax errors Run-time errors are reported by the PL/SQL run-time engine are

handled in the EXCEPTION section of the program code Compile errors start with the prefix PLS Run-time errors have the prefix of ORA

Handling Runtime Errors is PL/SQL Programs

Page 83: ITBIS373 Database Development

83

Handling Runtime Errors is PL/SQL Programs

Specific runtime error message

Error code that signifies a runtime error

Page 84: ITBIS373 Database Development

84

When a runtime error occurs, an exception, or unwanted event, is raised

Program control immediately transfers to the program’s exception section where exception handlers exist to deal with or handle different error situations

An exception handler contains one or more commands that provide operation instructions when a specific exception is raised

It could correct the error or notify the user of the problem, or it could inform the user of the error and allow the user to decide on the action to take

Handling Runtime Errors is PL/SQL Programs

Page 85: ITBIS373 Database Development

85

There are three types of errors or exceptions that can be handled: Predefined exceptions Undefined exceptions User-defined exceptions

Handling Runtime Errors is PL/SQL Programs

Page 86: ITBIS373 Database Development

86

These are the most common errors that occur in programs

The PL/SQL language assigns an exception name and a built-in exception handler for each predefined exception

These are defined on the next slide

Predefined Exceptions

Page 87: ITBIS373 Database Development

87

Predefined Exceptions

Oracle Error Code Exception Name Description

ORA-00001 DUP_VAL_ON_INDEX Unique constraint on primary key violated

ORA-01001 INVALID_CURSOR Illegal cursor operation

ORA-01403 NO_DATA_FOUND Query returns no records

ORA-01422 TOO_MANY_ROWS Query returns more rows than anticipated

ORA-01476 ZERO_DIVIDE Division by zero

ORA-01722 INVALID_NUMBER Invalid number operation

ORA-06502 VALUE_ERROR Error in truncation, arithmetic or conversion operation

Page 88: ITBIS373 Database Development

88

Predefined Exceptions When an exception is raised program control is immediately transferred to the

EXCEPTION block of the program An exception handler is a specific series of commands that provide operation

instructions when an exception is raised Code can be written there to explicitly handle every anticipated exception as

well as other exceptions General format is:

EXCEPTION WHEN exception1_name THEN exception1 handling statements; WHEN exception2_name THEN exception handling statements; … WHEN OTHERS THEN exception handling statements;END;

Page 89: ITBIS373 Database Development

89

Predefined Exceptions

The combination of WHEN exception_name THEN and the associated error-handling statements is called an exception handler

WHEN OTHERS is the catch-all expression to handle non-specific errors

The error-handling statements make it easier to read the error problems

After an error is handled the program will terminate

Page 90: ITBIS373 Database Development

90

Predefined Exceptions

Program terminates because of the predefined runtime error, this can be handled in a more professional fashion using an exception handler

Specific predefined exception name

Page 91: ITBIS373 Database Development

91

Predefined Exceptions

When the error occurs, control is transferred to the EXCEPTION section where the handler for the specific error handles the error and presents the message to the user

Page 92: ITBIS373 Database Development

92

WHEN OTHERS for Handling Errors

During program development it is helpful to use the WHEN OTHERS exception handler to display the associated Oracle error message for unanticipated errors

To do this use the SQLERRM function This function returns character string that contains the Oracle

error code and the message for the most recent Oracle error generated

To use this function you must declare a VARCHAR2 character variable of 512 bytes to cover the longest Oracle error message

Page 93: ITBIS373 Database Development

93

WHEN OTHERS for Handling Errors

Page 94: ITBIS373 Database Development

94

Undefined Exceptions

Exceptions are common errors that have been given explicit names, which were listed several slides ago

Undefined exceptions are less common errors that have not been given an explicit exception name

Look at the following example on the next slide:

Page 95: ITBIS373 Database Development

95

Undefined Exceptions

The above error is used to demonstrate the handling of an undefined exception, the error code is ORA-02291 which is not a predefined error

Page 96: ITBIS373 Database Development

96

Undefined Exceptions

To handle an undefined exception, you must explicitly declare the exception in the DECLARE section of the program and associate it with a specific Oracle error code

Then you can create an error handler The syntax for declaring an exception is:

DECLARE

e_exception_name EXCEPTION;

PRAGMA EXCEPTION_INIT (e_exception_Name, Oracle_error_code);

Page 97: ITBIS373 Database Development

97

Undefined Exceptions The e_exception_name parameter can be any legal variable

name, usually user-declared exception names are prefixed with e_ to keep them for being confused with other variable names

The PRAGMA EXCEPTION_INIT command tells the interpreter to associate the given exception name with a specific Oracle error code

The Oracle_error_code parameter is the numeric code Oracle assigns to runtime errors

A complete listing of Oracle error codes is available on the Oracle web site as we previously discussed

Program to handle ORA-02291 error code

Page 98: ITBIS373 Database Development

98

Undefined Exceptions

The above PL/SQL script has been modified to handle the undefined exception for the ORA-02291 error code

Page 99: ITBIS373 Database Development

99

User-Defined Exceptions

User-defined exceptions are used to handle exceptions that will not cause Oracle Run-time errors

These will enforce business rules or to ensure integrity of the database

Northwoods student system has a rule that states a record can only be deleted from the ENROLMENT table if the grade is NULL, records with grades assigned cannot be deleted

Page 100: ITBIS373 Database Development

100

User-Defined Exceptions The general format is:

DECLARE e_exception_name EXCEPTION; other variable declarationsBEGIN other program statements IF undesirable condition THEN RAISE e_exception_name END IF; other program statementsEXCEPTION e_exception_name THEN error handling statementsEND;

Define the exception

Raise the exception

Handle the exception

Page 101: ITBIS373 Database Development

101

Define the exception in the DECLARE section using the same syntax used for the undefined exception

To raise the exception a IF/THEN decision is used to check the exception condition

If the exception condition is true the RAISE command raises the exception and transfers control to the exception section

The exception handler then executes and displays the error handling messages

User-Defined Exceptions

Page 102: ITBIS373 Database Development

102

User-Defined Exceptions

The above PL/SQL script id being used to demonstrate a user-defined exception, there is a rule surrounding the deletion of a record if the grade has a NOT NULL value, in other words the record has a grade

Page 103: ITBIS373 Database Development

103

Nested PL/SQL Program Blocks

Recall with exception handling as soon as the exception is raised, program control jumps to the EXCEPTION section, the exception is handled, and then the program terminates

Sometimes you need a program that has an exception handler that notifies the user when an exception is raised but continues execution

To do this you create a nested PL/SQL program block

Page 104: ITBIS373 Database Development

104

Nested PL/SQL Program Blocks

With nested PL/SQL program blocks one program block called an outer block, contains another PL/SQL program blocks called an inner block

An inner block must always be within the body (after the BEGIN command) of the outer block

A PL/SQL program can contain multiple nested program blocks

Page 105: ITBIS373 Database Development

105

Nested PL/SQL Program Blocks

DECLARE <VARIABLE DECLARATIONS>BEGIN <PROGRAM STATEMENTS> DECLARE <VARIABLE DECLARATIONS> BEGIN <PROGRAM STATEMENTS> EXCEPTION <ERROR HANDLING STATEMENTS> END;EXCEPTION <ERROR HANDLING STATEMENTS>END;

INNER BLOCK

Page 106: ITBIS373 Database Development

106

Nested PL/SQL Program Blocks

Recall that a variable is declared in the DECLARE section, a memory location associated with the variable name is established in main memory

When the program block’s END statement is reached the variable ‘s memory location is returned to the system and made available to other program blocks

With this in mind you must keep in mind the variable scope and persistence within a nested PL/SQL program

Page 107: ITBIS373 Database Development

107

Nested PL/SQL Program Blocks

Variable scope refers to the visibility of a variable to different program blocks

Variable persistence refers to when memory is set aside for a variable and when its memory is returned to the system

When a variable is declared in the outer block of a nested block program, memory is allocated to store the value associated with this variable

The outer block variable persists through all of the inner blocks Its memory is returned when the END statement for the outer

block is reached Outer block variable’s scope extends through its nested blocks

Page 108: ITBIS373 Database Development

108

Nested PL/SQL Program Blocks

Page 109: ITBIS373 Database Development

109

Nested PL/SQL Program Blocks

In rare cases a variable declared in an outer block will not be visible in a nested block

This happens when a variable in an inner block is given the same name as a variable in an outer block

In this situation the inners block’s variable is allocated its own memory location

Program statements in the inner block referencing this variable will return the inner block’s variable value rather than the out block’s value

The outer block value persists through the inner block but the visibility or scope does not extend to the inner block

Page 110: ITBIS373 Database Development

110

Nested PL/SQL Program Blocks

Page 111: ITBIS373 Database Development

111

Exception Handling in Nested Program Blocks

One of the main reasons for creating nested blocks is to facilitate exception handling

Placing exception handling in the inner block will cause the program to continue after the exception has been handled

A program is needed to look at the size of classes to determine whether or not a new room is required to accommodate the class

Exception handling will be placed in the inner block

Page 112: ITBIS373 Database Development

112

Exception Handling in Nested Program Blocks

Page 113: ITBIS373 Database Development

113

Exception Handling in Nested Program Blocks

DECLARE exception_ABEGIN <PROGRAM STATEMENTS> DECLARE <VARIABLE DECLARATIONS> BEGIN RAISE exception_A END;EXCEPTION <ERROR HANDLING STATEMENTS>END;

Declared in outer block

Raised in inner block

Handled in outer block

Page 114: ITBIS373 Database Development

114

Exception Handling in Nested Program Blocks

Exception handler is in outer block but raised in inner block

Page 115: ITBIS373 Database Development

115

Summary

PL/SQL is a programming language for working with an Oracle database

Scalar, composite and reference variables can be used The IF/THEN/ELSE decision control structure allows

branching logic Five loop constructs allow repeating code Cursors are returned from queries and can be explicitly

iterated over Exception handling is performed in the exception section.

User defined exceptions help to enforce business logic