If the test condition evaluates to TRUE, the sequence of statements is executed, and control is passed to the top of the loop for the next evaluation of the test condition.. If the test
Trang 1(section_id_seq.nextval, v_course, v_sec_num,v_instructor_id, SYSDATE, USER, SYSDATE, USER);
if number of sections added is ten exit the loop
EXIT WHEN v_sec_num = 10;
condi-Note that before you execute this version of the script you need to delete records from the
SECTION table that were added when you executed the original example If you did not run theoriginal script, you do not need to delete records from the SECTION table
The SECTION table has a unique constraint defined on the COURSE_NO and SECTION_NO
columns In other words, the combination of course and section numbers allows you to uniquelyidentify each row of the table When the original script is executed, it creates four records in theSECTION table for course number 430, section numbers 1, 2, 3, and 4 When the new version of thisscript is executed, the unique constraint defined on the SECTION table is violated because therealready are records corresponding to course number 430 and section numbers 1, 2, 3, and 4
Therefore, these rows must be deleted from the SECTION table as follows:
DELETE FROM section
WHERE course_no = 430AND section_no <= 4;
Trang 2(section_id, course_no, section_no, instructor_id,created_date, created_by, modified_date,
modified_by)VALUES
(section_id_seq.nextval, v_course, v_sec_num,v_instructor_id, SYSDATE, USER, SYSDATE, USER);
if number of sections added is ten exit the loopEXIT WHEN v_sec_num = 10;
END LOOP;
control resumes hereCOMMIT;
END;
E) How many times does the loop execute in this case?
ANSWER:The loop executes five times when even-numbered sections are added for the givencourse number
LAB 6.1
Lab 6.1 Exercises
123
Trang 3L A B 6 2
WHILE Loops
L A B O B J E C T I V E S
After completing this lab, you will be able to
Use WHILE loops
A WHILE loop has the following structure:
WHILE CONDITION LOOP
STATEMENT 1;STATEMENT 2;
STATEMENT N;END LOOP;
The reserved word WHILE marks the beginning of a loop construct The word CONDITION is the test condition of the loop that evaluates to TRUE or FALSE The result of this evaluation determines whether the loop is executed Statements 1 through N are a sequence of statements that is executed repeatedly The END LOOP is a reserved phrase that indicates the end of the loop construct.
This flow of logic is illustrated in Figure 6.3.
Figure 6.3 shows that the test condition is evaluated prior to each iteration of the loop If the test condition evaluates to TRUE, the sequence of statements is executed, and control is passed
to the top of the loop for the next evaluation of the test condition If the test condition ates to FALSE, the loop is terminated, and control is passed to the next executable statement following the loop.
evalu-As mentioned earlier, before the body of the loop can be executed, the test condition must be evaluated The decision as to whether to execute the statements in the body of the loop is made prior to entering the loop As a result, the loop is not executed if the test condition yields FALSE.
FOR EXAMPLE
DECLARE
v_counter NUMBER := 5;
BEGIN
WHILE v_counter < 5 LOOP
DBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
LAB 6.2
124
Trang 4decrement the value of v_counter by onev_counter := v_counter - 1;
Trang 5DID YOU KNOW?
Boolean expressions can also be used to determine when the loop should terminate
PREMATURE TERMINATION OF THE LOOP
The EXIT and EXIT WHEN statements can be used inside the body of a WHILE loop If the EXIT condition evaluates to TRUE before the test condition evaluates to FALSE, the loop is terminated prematurely If the test condition yields FALSE before the EXIT condition yields TRUE, there is no premature termination of the loop This is indicated as follows:
WHILE TEST_CONDITION LOOP
STATEMENT 1;STATEMENT 2;
IF EXIT_CONDITION THENEXIT;
LAB 6.2
126
WHILE Loops
Trang 6EXIT WHEN EXIT_CONDITION;END LOOP;
WHILE v_counter <= 5 LOOP
DBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
IF v_counter = 2 THENEXIT;
is evaluated, and as soon as the value of v_counterreaches 2, the loop is terminated.
Notice that according to the test condition, the loop should execute five times However, the loop is executed only twice, because the EXIT condition is present inside the body of the loop Therefore, the loop terminates prematurely.
Now try to reverse the test condition and EXIT condition as shown in the following example.
FOR EXAMPLE
DECLARE
v_counter NUMBER := 1;
BEGIN
WHILE v_counter <= 2 LOOP
DBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
v_counter := v_counter + 1;
IF v_counter = 5 THENEXIT;
Trang 7reaches 3, the test condition evaluates to FALSE, and the loop is terminated.
Both examples, when run, produce the following output:
v_counter = 1
v_counter = 2
PL/SQL procedure successfully completed
These examples demonstrate not only the use of the EXIT statement inside the body of the WHILE loop, but also a bad programming practice In the first example, the test condition can
be changed so that there is no need to use an EXIT condition, because essentially they both are used to terminate the loop In the second example, the EXIT condition is useless, because its terminal value is never reached You should never use unnecessary code in your program.
L A B 6 2 E X E R C I S E S
This section provides exercises and suggested answers, with discussion related to how those answersresulted The most important thing to realize is whether your answer works You should figure out theimplications of the answers and what the effects are of any different answers you may come up with
6.2.1 Use WHILE Loops
In this exercise, you use a WHILE loop to calculate the sum of the integers between 1 and 10
Create the following PL/SQL script:
DBMS_OUTPUT.PUT_LINE ('Current sum is: '||v_sum);
increment loop counter by onev_counter := v_counter + 1;
Trang 8DBMS_OUTPUT.PUT_LINE ('The sum of integers between 1 '||
'and 10 is: '||v_sum);
END;
Execute the script, and then answer the following questions:
A) What output appears on the screen?
ANSWER:The output should look like the following:
Current sum is: 1
Current sum is: 3
Current sum is: 6
Current sum is: 10
Current sum is: 15
Current sum is: 21
Current sum is: 28
Current sum is: 36
Current sum is: 45
Current sum is: 55
The sum of integers between 1 and 10 is: 55
PL/SQL procedure successfully completed
Every time the loop is run, the value of v_counteris checked in the test condition While thevalue of v_counteris less than or equal to 10, the statements inside the body of the loop areexecuted In this script, the value of v_sumis calculated and displayed on the screen Next, thevalue of v_counteris incremented, and control is passed to the top of the loop When the
value of v_counterincreases to 11, the loop is terminated
For the first iteration of the loop, the value of v_sumis equal to 1, according to the statementv_sum := v_sum + v_counter
After the value of v_sumis calculated, the value of v_counteris incremented by 1 Then, forthe second iteration of the loop, the value of v_sumis equal to 3, because 2 is added to the oldvalue of v_sum
After the loop has terminated,“The sum of integers ” is displayed on the screen
B) What is the test condition for this loop?
ANSWER:The test condition for this loop is v_counter <= 10
C) How many times did the loop execute?
ANSWER:The loop executed 10 times
As soon as the value of v_counterreaches 11, the test condition
v_counter <= 10
evaluates to FALSE, and the loop is terminated
As mentioned earlier, the loop counter tracks the number of times the loop is executed You willnotice that in this exercise, the maximum value of v_counteris equal to the number of timesthe loop is iterated
LAB 6.2
Lab 6.2 Exercises
129
Trang 9D) How many times will the loop execute
I) ifv_counteris not initialized?
II) ifv_counteris initialized to 0?
III) ifv_counteris initialized to 10?
ANSWER:
I) If the value of v_counteris not initialized to a value, the loop does not execute
For the loop to execute at least once, the test condition must evaluate to TRUE at leastonce If the value of v_counteris only declared and not initialized, it is NULL It is impor-tant to remember that null variables cannot be compared to other variables or values
Therefore, the test conditionv_counter <= 10never evaluates to TRUE, and the loop is not executed
II) If v_counteris initialized to 0, the loop executes 11 times instead of 10, because theminimum value of v_counterhas decreased by 1
Whenv_counteris initialized to 0, the range of integers for which the test condition ofthe loop evaluates to TRUE becomes 0 to 10 The given range of the integers has 11numbers As a result, the loop iterates 11 times
III) If v_counteris initialized to 10, the loop executes once
When the initial value of v_counterequals 10, the test condition evaluates to TRUE forthe first iteration of the loop Inside the body of the loop, the value of v_counterisincremented by 1 As a result, for the second iteration of the loop, the test condition evalu-ates to FALSE, because 11 is not less than or equal to 10, and control is passed to the nextexecutable statement after the loop
E) How does the value of v_sumchange based on the initial value of v_counterfrom the
preceding question?
ANSWER:Whenv_counteris not initialized, the loop is not executed Therefore, the value of
v_sumdoes not change from its initial value; it stays 0
Whenv_counteris initialized to 0, the loop is executed 11 times The value of v_sumis lated 11 times as well However, after the loop completes, the value of v_sumis 55, because 0 isadded to v_sumduring the first iteration of the loop
calcu-Whenv_counteris initialized to 10, the loop is executed once As a result, the value of v_sum
is incremented only once by 10 After the loop is complete, the value ofv_sumis equal to 10
F) What is the value of v_sumif it is not initialized?
ANSWER:The value of v_sumis NULL if it is not initialized to some value
The value of v_sumin the statement
v_sum := v_sum + 1
is always equal to NULL, because NULL + 1 is NULL It was mentioned previously that NULL ables cannot be compared to other variable or values Similarly, calculations cannot be performed
vari-on null variables
G) How would you change the script to calculate the sum of the even integers between 1 and 100?
ANSWER:The script should be similar to the following Changes are shown in bold
Notice that the value of v_counteris initialized to 2, and with each iteration of the loop, thevalue of v_counteris incremented by 2 as well
LAB 6.2
130
Lab 6.2 Exercises
Trang 10DBMS_OUTPUT.PUT_LINE ('Current sum is: '||v_sum);
increment loop counter by two
Trang 11L A B 6 3
Numeric FOR Loops
L A B O B J E C T I V E S
After completing this lab, you will be able to
Use numeric FOR loops with the IN option
Use numeric FOR loops with the REVERSE option
A numeric FOR loop is called numeric because it requires an integer as its terminating value Its structure is as follows:
FOR loop_counter IN [REVERSE] lower_limit upper_limit LOOP
STATEMENT 1;STATEMENT 2;
STATEMENT N;END LOOP;
The reserved word FOR marks the beginning of a FOR loop construct The variable
loop_counteris an implicitly defined index variable There is no need to define the loop counter in the declaration section of the PL/SQL block This variable is defined by the loop construct. lower_limit and upper_limit are two integer numbers or expressions that evaluate to integer values at runtime, and the double dot ( ) serves as the range operator.
lower_limit and upper_limit define the number of iterations for the loop, and their values are evaluated once, for the first iteration of the loop At this point, it is determined how many times the loop will iterate Statements 1 through N are a sequence of statements that is executed repeatedly END LOOP is a reserved phrase that marks the end of the loop construct The reserved word IN or IN REVERSE must be present when the loop is defined If the REVERSE keyword is used, the loop counter iterates from the upper limit to the lower limit However, the syntax for the limit specification does not change The lower limit is always refer- enced first This flow of logic is illustrated in Figure 6.4.
LAB 6.3
132
Trang 12FIGURE 6.4
Numeric FOR loop
Figure 6.4 shows that the loop counter is initialized to the lower limit for the first iteration of the loop only However, the value of the loop counter is tested for each iteration of the loop As long as the value of v_counterranges from the lower limit to the upper limit, the statements inside the body of the loop are executed When the value of the loop counter does not satisfy the range specified by the lower limit and the upper limit, control is passed to the first executable statement outside the loop.
Trang 13FOR EXAMPLE
BEGIN
FOR v_counter IN 1 5 LOOP
DBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
END LOOP;
END;
In this example, there is no declaration section for the PL/SQL block because the only variable used,v_counter, is the loop counter Numbers 1 5 specify the range of the integer numbers for which this loop is executed.
Notice that there is no statement
PL/SQL procedure successfully completed
As a matter of fact, if you include the statement
Trang 14PLS-00363: expression 'V_COUNTER' cannot be used as an assignment
target
ORA-06550: line 3, column 7:
PL/SQL: Statement ignored
WATCH OUT!
It is important to remember that the loop counter is implicitly defined and incremented when a
numeric FOR loop is used As a result, it cannot be referenced outside the body of the FOR loop
Consider the following example:
END;
When this example is run, the following error message is produced:
('Counter outside the loop is '||v_counter);
*ERROR at line 6:
ORA-06550: line 6, column 40:
PLS-00201: identifier 'V_COUNTER' must be declared
ORA-06550: line 5, column 4:
PL/SQL: Statement ignored
Because the loop counter is declared implicitly by the loop, the variable v_countercannot be
referenced outside the loop As soon as the loop completes, the loop counter ceases to exist
USING THE REVERSE OPTION IN THE LOOP
Earlier in this section, you encountered two options that are available when the value of the loop counter is evaluated, IN and IN REVERSE You have seen examples that demonstrate the usage
of the IN option for the loop The next example demonstrates the usage of the IN REVERSE option for the loop.
FOR EXAMPLE
BEGIN
FOR v_counter IN REVERSE 1 5 LOOP
DBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
Trang 15v_counter = 2
v_counter = 1
PL/SQL procedure successfully completed
As mentioned, even though the REVERSE keyword is present, the lower limit of the loop is referenced first However, it is important to note that the loop counter is evaluated from the upper limit to the lower limit For the first iteration of the loop, v_counter(in our case it is
a loop counter) is initialized to 5 (upper limit) Then its value is displayed on the screen For the second iteration of the loop, the value of v_counteris decreased by 1 and displayed on the screen.
Notice that the number of times the body of the loop is executed is not affected by the option used, IN or IN REVERSE Only the values assigned to the lower limit and the upper limit deter- mine how many times the body of the loop is executed.
PREMATURE TERMINATION OF THE LOOP
The EXIT and EXIT WHEN statements covered in the previous labs can be used inside the body
of a numeric FOR loop as well If the EXIT condition evaluates to TRUE before the loop counter reaches its terminal value, the FOR loop is terminated prematurely If the loop counter reaches its terminal value before the EXIT condition yields TRUE, the FOR loop doesn’t terminate prematurely Consider the following:
FOR LOOP_COUNTER IN LOWER_LIMIT UPPER_LIMIT LOOP
STATEMENT 1;STATEMENT 2;
IF EXIT_CONDITION THENEXIT;
Trang 16FOR EXAMPLE
BEGIN
FOR v_counter IN 1 5 LOOP
DBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
EXIT WHEN v_counter = 3;
END LOOP;
END;
Notice that according to the range specified, the loop should execute five times However, the loop is executed only three times because the EXIT condition is present inside the body of the loop Thus, the loop terminates prematurely.
L A B 6 3 E X E R C I S E S
This section provides exercises and suggested answers, with discussion related to how those answersresulted The most important thing to realize is whether your answer works You should figure out theimplications of the answers and what the effects are of any different answers you may come up with
6.3.1 Use Numeric FOR Loops with the IN Option
In this exercise, you use a numeric FOR loop to calculate a factorial of 10 (10! = 1*2*3 *10)
Create the following PL/SQL script:
END;
Execute the script, and then answer the following questions:
A) What output appears on the screen?
ANSWER:The output should look like the following:
Factorial of ten is: 3628800
PL/SQL procedure successfully completed
LAB 6.3
Lab 6.3 Exercises
137
Trang 17Every time the loop is run, the value of v_counteris incremented by 1 implicitly, and the
current value of the factorial is calculated As soon as the value of v_counterincreases to 10,the loop is run for the last time At this point, the final value of the factorial is calculated, and theloop is terminated After the loop has terminated, control is passed to the first statement outsidethe loop—in this case, DBMS_OUTPUT.PUT_LINE
B) How many times did the loop execute?
ANSWER:The loop executed ten times according to the range specified by the loop’s lower andupper limits In this example, the lower limit equals 1, and the upper limit equals 10
C) What is the value of the loop counter before the loop?
ANSWER:The loop counter is defined implicitly by the loop Therefore, before the loop, the loopcounter is undefined and has no value
D) What is the value of the loop counter after the loop?
ANSWER:Similarly, after the loop has completed, the loop counter is undefined again and canhold no value
E) How many times does the loop execute if the value of v_counteris incremented by 5 insidethe body of the loop?
ANSWER:If the value of v_counteris incremented by 5 inside the body of the loop, the
PL/SQL block does not compile successfully As a result, it does not execute
In this example, variable v_counteris a loop counter Therefore, its value can be incrementedonly implicitly by the loop Any executable statement that causes v_counterto change its
current value leads to compilation errors
F) Rewrite this script using the REVERSE option What will the value of v_factorialbe after theloop is completed?
ANSWER:The script should look similar to the following Changes are shown in bold
The value of v_factorialequals 3628800 after the loop is completed
FOR v_counter IN REVERSE 1 10 LOOP
v_factorial := v_factorial * v_counter;
END LOOP;
control resumes hereDBMS_OUTPUT.PUT_LINE('Factorial of ten is: '||v_factorial);
END;
This script produces the following output:
Factorial of ten is: 3628800
PL/SQL procedure successfully completed
The value of v_factorialcomputed by this loop is equal to the value of v_factorial
computed by the original loop You will notice that in some cases it does not matter which option,
IN or REVERSE, you use to obtain the final result You will also notice that in other cases, the resultproduced by the loop can differ significantly
LAB 6.3
138
Lab 6.3 Exercises
Trang 186.3.2 Use Numeric FOR Loops with the REVERSE Option
In this exercise, you use the REVERSE option to specify the range of numbers used by the loop to iterate.You display a list of even numbers starting from 10 and going to 0 Try to answer the questions beforeyou run the script After you have answered the questions, run the script and check your results
Create the following PL/SQL script:
IF MOD(v_counter, 2) = 0 THENDBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
As in the previous exercises, answer the following questions, and then execute the script:
A) What output appears on the screen?
ANSWER:The output should look like the following:
PL/SQL procedure successfully completed
Notice that the values of v_counterare displayed in decreasing order from 10 to 0 becausethe REVERSE option is used Remember that, regardless of the option used, the lower limit is
referenced first
B) How many times does the body of the loop execute?
ANSWER:The body of the loop executes 11 times, because the range of the integer numbersspecified varies from 0 to 10
C) How many times is the value of v_counterdisplayed on the screen?
ANSWER:The value of v_counteris displayed on the screen six times, because the IF ment evaluates to TRUE only for even integers
state-D) How would you change this script to start the list from 0 and go up to 10?
ANSWER:The script should look similar to the following Changes are shown in bold
To start the list of integers from 0 and go up to 10, the IN option needs to be used in the loop:
Trang 19FOR v_counter IN 0 10 LOOP
if v_counter is even, display its value on the screen
IF MOD(v_counter, 2) = 0 THENDBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
PL/SQL procedure successfully completed
Notice that when the IN option is used, the value of v_counteris initialized to 0, and, with eachiteration of the loop, it is incremented by 1 When the REVERSE option is used,v_counterisinitialized to 10, and its value is decremented by 1 with each iteration of the loop
E) How would you change the script to display only odd numbers on the screen?
ANSWER:The script should look similar to the following Changes are shown in bold
Trang 20Notice that only the test condition of the IF statement is changed to display the list of odd gers, and the following output is produced:
PL/SQL procedure successfully completed
F) How many times does the loop execute in this case?
ANSWER:In this case the loop executes 11 times
Based on the test condition used in the IF statement, even or odd integers are displayed on thescreen Depending on the test condition, the number of times v_counteris displayed on thescreen varies However, the loop is executed 11 times as long as the number range specified is 0
to 10
LAB 6.3
Lab 6.3 Exercises
141
Trang 21142 Try it Yourself
Trang 22a new PL/SQL feature introduced in Oracle 11g called the CONTINUE tion Similar to the EXIT condition, the CONTINUE condition has two forms, CONTINUE and CONTINUE WHEN, and it may be used inside the body of the loop only You will also learn how to nest these types of loops inside one another.
Trang 23condi-L A B 7 1
The CONTINUE Statement
L A B O B J E C T I V E S
After completing this lab, you will be able to
Use the CONTINUE statement
Use the CONTINUE WHEN statement
As mentioned previously, the CONTINUE condition has two forms: CONTINUE and CONTINUE WHEN.
THE CONTINUE STATEMENT
The CONTINUE statement causes a loop to terminate its current iteration and pass control to the next iteration of the loop when the CONTINUE condition evaluates to TRUE The CONTINUE condition is evaluated with the help of an IF statement When the CONTINUE condition evaluates to TRUE, control is passed to the first executable statement in the body of the loop This is indicated by the following:
LOOP
STATEMENT 1;STATEMENT 2;
IF CONTINUE_CONDITION THENCONTINUE;
END IF;
EXIT WHEN EXIT_CONDITION;
END LOOP;
STATEMENT 3;
In this example, you can see that after the CONTINUE condition evaluates to TRUE, control is
passed to STATEMENT 1, which is the first executable statement inside the body of the loop In
this case, it causes partial execution of the loop as the statements following the CONTINUE condition inside the body of the loop are not executed.
Trang 24LOOPDBMS_OUTPUT.PUT_LINE ('v_counter = '||v_counter);
THE CONTINUE WHEN STATEMENT
The CONTINUE WHEN statement causes a loop to terminate its current iteration and pass control to the next iteration of the loop only if the CONTINUE WHEN condition evaluates to TRUE Control is then passed to the first executable statement inside the body of the loop The structure of a loop using a CONTINUE WHEN clause is as follows:
LOOP
STATEMENT 1;STATEMENT 2;CONTINUE WHEN CONTINUE_CONDITION;EXIT WHEN EXIT_CONDITION;
END LOOP;
STATEMENT 3;
Figure 7.1 shows the flow of logic from the CONTINUE and CONTINUE WHEN statements Figure 7.1 shows that during each iteration, the loop executes a sequence of statements Control
is then passed to the CONTINUE condition of the loop If the CONTINUE condition evaluates
to TRUE, control is passed to the top of the loop The sequence of statements is executed edly until the CONTINUE condition evaluates to FALSE When the CONTINUE condition eval- uates to FALSE, control is passed to the next executable statement in the body of the loop, which
repeat-in this case evaluates the EXIT condition.
As mentioned earlier, Figure 7.1 illustrates that the flow of logic for the CONTINUE and CONTINUE WHEN statements is the same In other words,
Trang 25FIGURE 7.1
A simple loop with the CONTINUE condition
WATCH OUT!
The CONTINUE and CONTINUE WHEN statements are valid only when placed inside a loop When
placed outside a loop, they cause a syntax error To avoid this error, use the RETURN statement, asshown in the preceding chapter
DID YOU KNOW?
That CONTINUE and CONTINUE WHEN statements can be used with all types of loops
L A B 7 1 E X E R C I S E S
This section provides exercises and suggested answers, with discussion related to how those answersresulted The most important thing to realize is whether your answer works You should figure out theimplications of the answers and what the effects are of any different answers you may come up with
7.1.1 Use the CONTINUE Statement
In this exercise, you use a modified version of the ch06_1a.sql script you created in the previous chapter.The original script uses the EXIT condition to terminate a simple loop, and a special variable,
v_counter, which keeps count of the loop iterations With each iteration of the loop, the value of
next statement
is continue condition true
is exit condition true