if/then - eiu

12
1 Chapter 4B: More Advanced PL/SQL Programming © Abdou Illia MIS 4200 - Spring 2015 Monday 2/23/2015 2 Lesson B Objectives After completing this lesson, you should be able to: Create PL/SQL decision control structures Use SQL queries in PL/SQL programs Create loops in PL/SQL programs Create PL/SQL tables and tables of records Use cursors to retrieve database data into PL/SQL programs Use the exception section to handle errors in PL/SQL programs 3 IF/THEN Decision control structures Alter order in which statements execute Based on values of certain variables Syntax: IF condition THEN commands that execute if condition is TRUE; END IF; Condition Expression evaluates to TRUE or FALSE If TRUE commands execute

Upload: others

Post on 22-Nov-2021

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: IF/THEN - EIU

1

Chapter 4B: More Advanced PL/SQL Programming

© Abdou Illia MIS 4200 - Spring 2015

Monday 2/23/2015

2

Lesson B Objectives

After completing this lesson, you should be able to:• Create PL/SQL decision control structures• Use SQL queries in PL/SQL programs• Create loops in PL/SQL programs• Create PL/SQL tables and tables of records• Use cursors to retrieve database data into PL/SQL

programs• Use the exception section to handle errors in

PL/SQL programs

3

IF/THEN• Decision control structures

– Alter order in which statements execute– Based on values of certain variables

• Syntax:IF condition THENcommands that execute if condition is TRUE;

END IF;• Condition

– Expression evaluates to TRUE or FALSE– If TRUE commands execute

Page 2: IF/THEN - EIU

2

• Question: What two lines do you need to change to make the program display Today is not Friday when the current day is different than Friday?

4

5

IF/THEN/ELSE• Syntax:

IF condition THEN

commands that execute if condition is TRUE;

ELSE

commands that execute if condition is FALSE;

END IF;

• Evaluates ELSE command if condition FALSE

Nested IF/THEN/ELSE• Placing one or more IF/THEN/ELSE statements

within program statements that execute after IF or ELSE command

• Important to properly indent program lines

IF/THEN/ELSE

Page 3: IF/THEN - EIU

3

Nested IF/THEN/ELSE

8

IF/ELSIF

9

Logical Operators AND, OR, and NOT• Create complex expressions for decision control structure

condition• AND: Expressions on both sides of operator must be true

for combined expression to be TRUE• OR: Expressions on either side of operator must be true

for combined expression to be TRUE• Order of evaluation (precedence):

– NOT– AND– OR

• Parentheses can be used to override precedence and force the program to evaluate the OR first

Page 4: IF/THEN - EIU

4

10

Using SQL Queries in PL/SQL Programs

• Use SQL action query– Put query or command in PL/SQL program

– Use same syntax as the syntax used to execute query or command in SQL*Plus

– Can use variables instead of literal values like ‘Tammy’• To specify data values INSERT INTO Student (s_first)

VALUES (curr_first_name);

WHERE s_first = curr_first_name;

Changing the values one by one and adding them to the table requires a lot of coding. What is the best way of handling this kind of repetitive job in programming?

12

Loops• Systematically executes program statements

• Periodically evaluates exit condition to determine if loop should repeat or exit

• Pretest loop– Evaluates exit condition before any program

commands execute

• Posttest loop– Executes program commands before loop evaluates

exit condition for first time

• PL/SQL has 5 types of loop structures:– LOOP…EXIT - WHILE…LOOP

– LOOP…EXIT WHEN - Numeric FOR loop

– Cursor FOR loop

Page 5: IF/THEN - EIU

5

The LOOP...EXIT Loop

• Pretest or posttest• Syntax:

CREATE TABLE count_table(counter NUMBER(2));

SQL statement LOOP[program statements]IF condition THENEXIT;

END IF;[additional program

statements]END LOOP;

Syntax

The LOOP...EXIT WHEN Loop

LOOPprogram statementsEXIT WHEN condition;

END LOOP;

Syntax (posttest loop)

The WHILE...LOOP

• WHILE…LOOP is a Pretest loop

WHILE condition LOOPprogram statements

END LOOP;

Syntax

Q: Why the SELECT * FROM count_table shows only counter 6 to 10?

Page 6: IF/THEN - EIU

6

The Numeric FOR Loop• Does not require explicit counter increment

FOR counter_variable IN start_value .. end_valueLOOP

program statementsEND LOOP;

Syntax

Cursor

• A pointer to memory location on database server

• Used to: – Retrieve and manipulate database data in PL/SQL

programs

• Types:– Implicit cursor

– Explicit cursor

Implicit Cursors• Context area

– A memory location created by INSERT, UPDATE, DELETE, or SELECT

– Contains information about query (# rows, etc.)

• Active set

– Set of data rows that query retrieves when a SELECT query is issued

• Implicit cursor

– A pointer to the context area

– Called so, because you do not need to write code to explicitly create the cursor or retrieve its values

– Used to assign output of SELECT query to PL/SQL program variables when query will return only one record*

* Error occurs if query returns no records or more than one record

Page 7: IF/THEN - EIU

7

Implicit Cursors (continued)

• To retrieve data using implicit cursor in PL/SQL, you add an INTO clause to the SELECT query

• Syntax:SELECT field1, field2, ...

INTO variable1, variable2, ...

FROM table1, table2, ...

WHERE join_conditions

AND search_condition_to_retrieve_1_record;

• Variables must be declared in Declaration section

• Variables must have same data types as fields

• To avoid errors, %TYPE reference data type should be used

Implicit Cursors (continued)

Explicit Cursors

• Retrieve and display data in PL/SQL programs for query that might– Retrieve multiple records

– Return no records at all

• Must explicitly write the code to– Declare cursor

– Open cursor

– Fetch data rows

– Close cursor

Page 8: IF/THEN - EIU

8

Explicit Cursors (continued)

• Declare explicit cursor syntax:– CURSOR cursor_name IS select_query;

• Open explicit cursor syntax:– OPEN cursor_name;

• Fetch values using LOOP…EXIT WHEN loop:LOOP

FETCH cursor_name INTO variable_name(s);

EXIT WHEN cursor_name%NOTFOUND;• Close cursor syntax:

– CLOSE cursor_name;

Note: When the cursor is declared, system doesn’t check errors in the query. It creates the memory structure to store the active set. The PL/SQL interpreter checks for error and interprets the query when opening the cursor

Q: At this point, what is the value for current_bldg_code?

The declared variable is used to retrieve the cursor content and to display

• Using %ROWTYPE variable to display explicit cursor values

Using a cursor and a single variable to retrieve multiple fields values

Page 9: IF/THEN - EIU

9

Handling Runtime Errors in PL/SQL Programs

• Runtime errors– Occur when an exception (unwanted event) is raised

– Cause program to fail during execution

• Possible causes (exceptions):– Division by zero - inserting incompatible data

– Constraint violation - retrieving 0/several rows with implicit cursor

• Exception handling– Programmers place commands in EXCEPTION section

• Handle exception options– Correct error without notifying user of problem

– Inform user of error without taking corrective action

• After exception handler executes– Program ends

DECLAREvariable declarations

BEGINprogram statements

EXCEPTIONerror-handling statements

END;

• Handling error procedure depends the type of exception:– Predefined exception - undefined exception– User-defined exception

Predefined Exceptions• Most common errors that occur in programs

• PL/SQL language: – Assigns exception name

– Provides built-in exception handler for each predefined exception

• System automatically displays error message informing user of nature of problem

Page 10: IF/THEN - EIU

10

Exception Handler Syntax• Can create exception handlers to display alternate

error messages

Using the WHEN OTHERS exception• The SQLERRM built-in function is used to handle other exception• To use the SQLERRM function, you must

– Declare a VARCHAR2 variable– Assign the declared variable the error’s text and code

Page 11: IF/THEN - EIU

11

Undefined Exceptions

• Less common errors

• Do not have predefined names

• Must explicitly declare exception in program’s declaration section

• Associate new exception with specific Oracle error code

• Create exception handler in exception section – Using same syntax as for predefined exceptions

Example of undefined exception

Loc_id 60 doesn’t exist in LOCATION

• The ORA-02291 exception is not predefined.

• Need to explicitly declare the exception and write a handler

Creating an exception handlerDECLARE

e_exception_name EXCEPTION;PRAGMA EXCEPTION_UNIT(e_exception_name, -Oracle_error_code);

Syntax

Page 12: IF/THEN - EIU

12

User-defined Exceptions

• Used to handle an exception that – Does not raise Oracle runtime error

– But requires exception handling to• Enforce business rules or

• Ensure integrity of database

• Example:– Internal Northwoods’ rule is “Users can delete row

from the ENROLLMENT table only if s_grade is NULL”

– Trying to delete a delete an ENROLLMENT row where the s_grade is not NULL will raise an exception that needs to be handled