1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu controlling flow in PL / SQL pdf

34 344 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Controlling Flow in PL/SQL Blocks
Trường học Oracle University
Chuyên ngành Database Management
Thể loại Giáo trình
Định dạng
Số trang 34
Dung lượng 232,38 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

This lesson addresses two types of PL/SQL control structures: D Conditional constructs with the IF statement D Looping constructs D Basic loop to provide repetitive actions without overa

Trang 1

Controlling Flow in PL/SQL

Blocks

23

Trang 2

Schedule: Timing Topic

40 minutes Lecture

60 minutes Practice

100 minutes Total

Class Management Note:

Files required for lesson

Demonstration: l23calc.pls, l23iters.pls

Practice: None

Trang 3

You can control the flow of your PL/SQL block by using conditional statements and loops.

At the end of this lesson, you should be able to

D Conditionally control processing in a PL/SQL block

D Iterate statements by using various types of loops

Trang 4

Class Management Note:

The GOTO statement is not addressed in this course because unconditionalbranching goes against the procedural structure of a top-down languagesuch as PL/SQL You can mention the GOTO statement It unconditionallytransfers control to a different sequence of statements Branch to a labelwithin the same block or to a sequence of statements, or to a label within anouter block or enclosing sequence of statements

Trang 5

You can change the logical flow of statements within the PL/SQL block with a

number of control structures This lesson addresses two types of PL/SQL control

structures:

D Conditional constructs with the IF statement

D Looping constructs

D Basic loop to provide repetitive actions without overall conditions

D FOR loops to provide for iterative control of actions based upon a count

D WHILE loops to provide iterative control of actions based on a true statement

D EXIT statement to terminate loops

For more information, see

PL/SQL User’s Guide and Reference, Release 2.3, Chapter 3 “Control Structures.”

Trang 6

Class Management Note:

PowerPoint: This slide uses the build feature

Trang 7

The IF Statement

The structure of the PL/SQL IF statement is similar to the structure of IF statements

in other procedural languages It allows PL/SQL to perform actions selectively basedupon conditions

D When writing code, remember the spelling of the keywords

D ELSIF is one word

D END IF is two words

D If the controlling Boolean condition is TRUE, the associated sequence of

statements is executed; if the controlling Boolean condition is FALSE or NULL,the associated sequence of statements is passed over

D Any number of ELSIF clauses are permitted

D There can be at most one ELSE clause

D Indent the conditionally executed statements for clarity

Trang 9

The IF Statement continued

Simple IF Statements

PL/SQL executes the conditional statements only if the condition is TRUE If thecondition is FALSE or NULL, then PL/SQL ignores the conditional statements Ineither case, control resumes at the next statement in the program following END IF

Example

Set the job title to Sales Representative and the region number to 35 if the last name

is Dumas

.

IF v_last_name = ’Dumas’ THEN

v_job := ’Sales Representative’;

Trang 10

Class Management Note:

DEMO: l23calc.pls

PURPOSE: Use a function to return a calculated value based on an inputvalue

1 Select from the menu File—>Load, and load the l23calc.pls.

2 Show the code to the students

3 Create a variable to hold the returned calculated number

Enter: .CREATE NUMBER x PRECISION 5

4 Execute the function at the interpreter

Trang 11

The IF Statement continued

Nested IF Statements

Either set of actions of the result of the first IF statement can include further IF

statements before specific actions are performed Each nested IF statement must beterminated with a corresponding END IF

IFĆTHENĆELSIF Statements

When possible, however, use the ELSIF clause instead of nesting IF statements Thecode is easier to read and understand The logic is clearly identified If the action inthe ELSE clause consists purely of another IF statement, it is more convenient to usethe ELSIF clause This makes the code clearer by removing the need for nested ENDIFs at the end of each further set of conditions and actions

Trang 13

Building Logical Conditions

Build a simple Boolean condition by combining number, character, or date

expressions with a comparison operator In general, handle null values with the ISNULL operator

Null Within Expressions and Comparisons

D Any expression containing a null value evaluates to NULL, with the exception of

a concatenated expression, which treats the null value as the empty string

D Any simple comparison containing a null value evaluates to NULL

D An IS NULL comparison evaluates to TRUE or FALSE

Boolean Conditions with Logical Operators

Build a complex Boolean condition by combining simple Boolean conditions with thelogical operators AND, OR, and NOT In the accompanying logic tables, FALSEtakes precedence for an AND condition and TRUE takes precedence in an OR

condition

Class Management Note:

The negation of NULL (NOT NULL) results in a null value because nullvalues are indeterminate

Trang 14

Class Management Note:

PowerPoint: This slide uses a build feature to present the solutions in redunder the column VALUE Ask the students the value for V_FLAG beforerevealing the answer

Trang 15

Building Logical Conditions continuedThe AND logic table can help you evaluate the possibilities for the Boolean conditionyou see below.

.

v_flag := v_reorder_flag AND v_available_flag;

.

Trang 17

above it This uncontrolled loop is an infinite loop that is to be avoided To avoid an

infinite loop, add an EXIT statement

The EXIT Statement

You can terminate a loop using the EXIT statement Control passes to the next

statement after the END LOOP statement You can issue EXIT either as an actionwithin an IF statement, or as a standalone statement within the loop In the latter case,you can attach a WHEN clause to allow conditional termination of the loop

Class Management Note:

PowerPoint: This slide uses the build feature on the syntax

Trang 19

Loop Statements continued

INSERT INTO s_item (ord_id, item_id)

VALUES (v_ord_id, v_counter);

v_counter := v_counter + 1;

EXIT WHEN v_counter > 10;

END LOOP;

.

Trang 20

Class Management Note:

Let students know that they can also use the EXIT statement in all theseloops to set additional conditions to exit the loop

Another type of FOR loop is the cursor FOR loop, which is covered in alater lesson

Trang 21

Loop Statements continued

where: index is an implicitly declared integer whose value

automatically increases or decreases by 1 oneach iteration of the loop until the upper bound

is reached

REVERSE causes the index to decrement with each

iteration from the upper bound to the lowerbound

lower_bound specifies the lower bound for the range of index

The sequence of statements is executed each time the index is incremented,

as determined by the two bounds The lower bound and upper bound ofloop range can be literals, variables, or expressions, but must evaluate tointegers If the lower bound of loop range evaluates to a larger integer thanthe upper bound, the sequence of statements will not be executed

For example, this sequence of statements is executed once

FOR i IN 3 3 LOOP

statement1;

Trang 22

Class Management Note:

DEMO: l23iter.pls

PURPOSE: Show students the number of times the loop is executed Also,point out that the index is only referenced within the loop and that it can bereferenced within an expression

1 Select from the menu File—>Load, and load the l23iter.pls.

2 Show the code to the students

3 Execute the procedure at the interpreter Enter: iterate(3,10);

4 Execute the procedure at the interpreter Enter; iterate(4,4);

Trang 23

Loop Statements continued

Example

Print the number of times the loop is executed and the last value for the index based

on the supplied lower bound and upper bound

D Reference the index within the loop only; it is undefined outside the loop

D Reference the existing value of an index within an expression

D Do not reference the index as the target of an assignment.

Class Management Note:

Emphasize that the value of the index automatically increases by 1 on eachiteration of the loop till the upper bound is reached

Note that because “i” is such a traditional name for the index of a numericFOR loop, the convention for naming variables with the “v_” prefix isrelaxed

Trang 24

Condition is evaluated at the beginning of each iteration.

Trang 25

Loop Statements continued

WHILE Loop

You can use the WHILE loop to repeat a sequence of statements until the controllingcondition is no longer TRUE The condition is evaluated at the start of each iteration.The loop terminates when the condition is FALSE If the condition is FALSE at thestart of the loop, then no further iterations are performed

Class Management Note:

Point out the differences between the WHILE and numeric FOR loops TheFOR loop has an implicit counter and automatically increments each timethrough the loop The WHILE loop has an explicit counter and must contain

a statement to increment the counter

Point out in the example that it is the same request as with the basic loop,but the method is different Also, highlight that there is no explicit EXIT

statement The condition determines when the loop is terminated.

Trang 27

Loop Statements continued

Nested Loops and Labels

You can nest loops to multiple levels You may nest FOR loops within WHILE loops,and WHILE loops within FOR loops Normally, the termination of a nested loop doesnot terminate the enclosing loop (unless an exception was raised) However, you canlabel loops and exit the outer loop with the EXIT statement

Label names follow the same rules as other identifiers A label is placed before astatement, either on the same line or a separate line Label loops by placing the label

before the word LOOP within label delimiters (<<label>>).

If the loop is labeled, the label name can optionally be included after the END LOOPstatement

EXIT Outer_loop WHEN total_done = ’YES’;

–– Leave both loops

EXIT WHEN inner_done = ’YES’;

–– Leave inner loop only

Trang 29

Control PL/SQL logic with the conditional structure and loops

Control Structure Description

IF-THEN-ELSE Executes a statement or sequence of statements

conditionally

Basic loop Repeats a statement or sequence of statements

indefinitely

EXIT statement Terminates a loop

FOR loop Repeats a statement or sequence of statements a fixed

number of times

WHILE loop Repeats a statement or sequence of statements until a

condition is no longer TRUE

Trang 31

Practice Overview

In this practice, you create procedures that incorporate loops and conditional controlstructures

Practice Contents

D Performing conditional actions using the IF statement

D Performing iterative steps by using the loop structure

D Viewing the values variables during runtime by using Procedure Builder

Trang 33

Practice 23

If you are not already connected to the database, be sure to do so now

1. Create a procedure named SET_COMM to conditionally set the commissionpercentage for a given employee based upon total sales

a. Prepare this exercise by disabling the constraint on the COMMISSION_PCTcolumn in the S_EMP table You modify the commission percentage to valuesthat are not in the constraint

PL/SQL> ALTER TABLE s_emp

+> DROP CONSTRAINT s_emp_commission_pct_ck;

b. Create a parameter to accept the employee number from the user

c. Find the sum of the totals for all orders placed by that employee

d. If the sum is less than 100,000, set the commission percentage for the

h. Commit the change

i. Test the block and view the changes Results should appear for some exampleemployees as follows:

Trang 34

b. Once the rows are updated, find out how many rows were updated Print thefollowing statements to the screen based on the number of rows updated.

i. If less than three rows updated, statement should read “Fewer than 3customer records updated for region number X”, where X represents theregion number

ii. Otherwise, it should read “Y rows updated for region number X”, where Y

is the number of rows updated, and X is the region number

c. Rollback the changes Set a breakpoint on the conditional test for the number

of rows updated Execute the procedure Check the Stack node to verify thevalues of the variables as you Step Into the statements in the loop

Reminder: You can use the Quick Tour, “Debugging a Program Unit” sectionfor assistance

If you have time, complete the following exercise

3. Create a procedure named EMP_MESSAGE that selects the employee last name,start date, and salary based on an employee number provided at execution Print amessage to the screen based on any combination of one of the following criteria.Test employee numbers 2, 5, 16, 17, and 18 Hint: A nested IF is required

Salary greater than 1200 Salary more than 1200

Last name contains “R” Name contains “R”

Start date is in March March start date

None of the above **None**

Ngày đăng: 21/12/2013, 06:17