Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 ITBIS373 Database Development Lecture 2 – Chapter 4B Introduction to PL/SQL."— Presentation transcript:

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

2 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

3 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

4 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

5 5 IF/THEN

6 6 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

7 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

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

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

10 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

11 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

12 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

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

14 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

15 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

16 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

17 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????

18 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

19 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

20 20 CategoryPurposeExample 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

21 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

22 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

23 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

24 24 Download Student Data Files Use the browser to go to www.course.com, select Databases from list on left framewww.course.com

25 25 Download Student Data Files Select Oracle in the centre area

26 26 Download Student Data Files Find the textbook for our course, and select that title

27 27 Download Student Data Files Select Download Student Files at the bottom of the screen

28 28 Download Student Data Files Select the link for Data Files for Students

29 29 Download Student Data Files Select Open to allow you to unzip the file to your hard drive

30 30 Download Student Data Files I choose to place mine in the same directory I had set up to store my PL/SQL work

31 31 Download Student Data Files It will place each chapter into its own folder

32 32 Download Student Data Files We need chapter 4 for the script that is needed for execution, EmptyNorthwoods.sql

33 33 Using SQL Queries in PL/SQL Programs Run the emptynorthwoods script that is provide in the student data files for this textbook

34 34 Using SQL Queries in PL/SQL Programs Check to see if the TERM table exists and that it is empty

35 35 Using SQL Queries in PL/SQL Programs Write the above PL/SQL program in Notepad and execute in SQL*Plus

36 36 Using SQL Queries in PL/SQL Programs Use a SELECT statement on the TERM table to see if the records exist

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

38 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

39 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

40 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

41 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 loop END 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

42 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

43 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

44 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

45 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

46 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

47 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

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

49 49 The Numeric FOR Loop The basic syntax for the command is: FOR counter variable IN start value.. end value LOOP program statements END 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

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

51 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

52 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

53 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

54 54 Implicit Cursors

55 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

56 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

57 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

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

59 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

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

61 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

62 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

63 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

64 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

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

66 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

67 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 statements END;

68 68 Fetching the Data Rows Using the %TYPE for processing in an explicit cursor

69 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 statements END;

70 70 Fetching the Data Rows Using the %ROWTYPE for processing in an explicit cursor

71 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

72 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

73 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

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

75 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

76 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 statements END LOOP;

77 77 Explicit Cursor Using a FOR LOOP Using the FOR LOOP for processing in an explicit cursor

78 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?

79 79 Other Explicit Cursor Attributes AttributeDescription %NOTFOUNDEvaluates as true when the cursor has no rows left to fetch, false when there are rows %FOUNDTrue when the cursor has rows to fetch and false when the cursor has no rows to fetch %ROWCOUNTReturns the number of rows the cursor has fetched so far %ISOPENReturns true if the cursor is open and false if the cursor is closed

80 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

81 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

82 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

83 83 Handling Runtime Errors is PL/SQL Programs Specific runtime error message Error code that signifies a runtime error

84 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

85 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

86 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

87 87 Predefined Exceptions Oracle Error CodeException NameDescription ORA-00001DUP_VAL_ON_INDEXUnique constraint on primary key violated ORA-01001INVALID_CURSORIllegal cursor operation ORA-01403NO_DATA_FOUNDQuery returns no records ORA-01422TOO_MANY_ROWSQuery returns more rows than anticipated ORA-01476ZERO_DIVIDEDivision by zero ORA-01722INVALID_NUMBERInvalid number operation ORA-06502VALUE_ERRORError in truncation, arithmetic or conversion operation

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

89 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

90 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

91 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

92 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

93 93 WHEN OTHERS for Handling Errors

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

95 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

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

97 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

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

99 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

100 100 User-Defined Exceptions The general format is: DECLARE e_exception_name EXCEPTION; other variable declarations BEGIN other program statements IF undesirable condition THEN RAISE e_exception_name END IF; other program statements EXCEPTION e_exception_name THEN error handling statements END; Define the exception Raise the exception Handle the exception

101 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

102 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

103 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

104 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

105 105 Nested PL/SQL Program Blocks DECLARE BEGIN DECLARE BEGIN EXCEPTION END; EXCEPTION END; INNER BLOCK

106 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

107 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

108 108 Nested PL/SQL Program Blocks

109 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

110 110 Nested PL/SQL Program Blocks

111 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

112 112 Exception Handling in Nested Program Blocks

113 113 Exception Handling in Nested Program Blocks DECLARE exception_A BEGIN DECLARE BEGIN RAISE exception_A END; EXCEPTION END; Declared in outer block Raised in inner block Handled in outer block

114 114 Exception Handling in Nested Program Blocks Exception handler is in outer block but raised in inner block

115 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


Download ppt "1 ITBIS373 Database Development Lecture 2 – Chapter 4B Introduction to PL/SQL."

Similar presentations


Ads by Google