SlideShare a Scribd company logo
1 of 113
Download to read offline
2
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
Database Programming with
PL/SQL
4-1
Conditional Control: IF Statements
3
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Objectives
•This lesson covers the following objectives:
−Describe a use for conditional control structures
−List the types of conditional control structures
−Construct and use an IF statement
−Construct and use an IF-THEN-ELSE statement
−Create PL/SQL to handle the null condition in IF statements
3
4
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Purpose
•In this section, you learn how to use the conditional
logic in a PL/SQL block
•Conditional processing extends the usefulness of
programs by allowing the use of simple logical tests to
determine which statements are executed
4
5
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Purpose
•Think of a logic test as something you do every day
•If you get up in the morning and it is cold outside, you
will choose to wear cold-weather clothing
•If you get up in the morning and it is warm outside, you
will choose to wear warm-weather clothing
•And if there is a chance of rain, then you will bring a
rain coat or an umbrella with you
5
The IF statement contains alternative courses of action in a block based on conditions. A condition
is an expression with a TRUE or FALSE value that is used to make a decision.
The CASE statement contains alternative courses of action in a block based on one condition. They
are different in that they can be used outside of a PLSQL block in a SQL statement.
LOOPs are control structures that allow iteration of statements. Loop control structures are
repetition statements that enable you to execute statements in a PLSQL block repeatedly. There
are three types of loop control structures supported by PL/SQL—BASIC, FOR, and WHILE.
6
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Controlling the Flow of Execution
•You can change the logical flow of statements within
the PL/SQL block with a number of control structures
•This lesson introduces three types of PL/SQL control
structures:
−Conditional constructs with the
IF statement
−CASE expressions
−LOOP control structures
6
FOR
LOOP
WHILE
Writing in pseudocode combines natural language with code-like elements. It is sometimes used
when introducing new structures and concepts. Pseudocode generally excludes syntax
requirements and adds words that capture the logic of the structure/concept under consideration.
7
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statement
•The IF statement shown below using "pseudocode"
contains alternative courses of action in a block based
on conditions
•A condition is an expression with a TRUE or FALSE
value that is used to make a decision
7
if the region_id is in (5, 13, 21)
then print "AMERICAS"
otherwise, if the region_id is in (11, 14, 15)
then print "AFRICA"
otherwise, if the region_id is in (30, 34, 35)
then print "ASIA"
Conditions
CASE expressions will be discussed more fully in a future lesson.
8
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
CASE Expressions
•CASE expressions are similar to IF statements in that
they also determine a course of action based on
conditions
•They are different in that they can be used outside of a
PLSQL block in an SQL statement
•Consider the following pseudocode example:
8
if the region_id is
5 then print "AMERICAS"
13 then print "AMERICAS"
21 then print "AMERICAS"
11 then print "AFRICA"
14 then print "AFRICA"
15 then print "AFRICA"
30 then print "ASIA" …
Loops will be discussed more fully in a future lesson.
9
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
LOOP Control Structures
•Loop control structures are repetition statements that
enable you to execute statements in a PLSQL block
repeatedly
•Three types of loop control structures are supported by
PL/SQL: BASIC, FOR, and WHILE
9
FOR
LOOP
WHILE
10
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
LOOP Control Structures
•Consider the following pseudocode example:
−Print the numbers 1–5 by using a loop and a counter
10
Loop Counter equals: 1
Loop Counter equals: 2
Loop Counter equals: 3
Loop Counter equals: 4
Loop Counter equals: 5
Statement processed.
FOR
LOOP
WHILE
Please note the ELSIF does not have an 'E' after the 'S,' and there is no space. There can be many
ELSIF clauses within an IF statement. There can be only one ELSE clause within an IF statement
(and it comes just before the END IF). Also, each THEN clause within the IF statement ends with a
semicolon.
11
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statements Structure
•The structure of the PL/SQL IF statement is similar to
the structure of IF statements in other procedural
languages
•It enables PL/SQL to perform actions selectively based
on conditions
•Syntax:
11
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
12
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statements
•Condition is a Boolean variable or expression that
returns TRUE, FALSE, or NULL
•THEN introduces a clause that associates the Boolean
expression with the sequence of statements that
follows it
12
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
13
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statements
•Statements can be one or more PL/SQL or SQL
statements
•They can include further IF statements containing
several nested IF, ELSE, and ELSIF statements
•The statements in the THEN clause are executed only if
the condition in the associated IF clause evaluates to
TRUE
13
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
14
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statements
•ELSIF is a keyword that introduces an additional
Boolean expression
•If the first condition yields FALSE or NULL, then the
ELSIF keyword introduces additional conditions
•ELSIF is the correct spelling, not ELSEIF
14
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
15
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statements
•ELSE introduces the default clause that is executed if,
and only if, none of the earlier conditions (introduced
by IF and ELSIF) are TRUE
•The tests are executed in sequence so that a later
condition that might be true is pre-empted by an
earlier condition that is true
•END IF; marks the end of an IF statement
15
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
16
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statements Note
•ELSIF and ELSE are optional in an IF statement
•You can have any number of ELSIF keywords but only
one ELSE keyword in your IF statement
• END IF marks the end of an IF statement and must be
terminated by a semicolon
16
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
17
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Simple IF Statement
•This is an example of a simple IF statement with a
THEN clause
•The v_myage variable is initialized to 31
17
DECLARE
v_myage NUMBER := 31;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child');
END IF;
END;
18
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Simple IF Statement
•The condition for the IF statement returns FALSE
because v_myage is not less than 11
•Therefore, the control never reaches the THEN clause
and nothing is printed to the screen
18
DECLARE
v_myage NUMBER := 31;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child');
END IF;
END;
19
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF THEN ELSE Statement
•The ELSE clause has been added to this example
•The condition has not changed, thus it still evaluates to
FALSE
19
DECLARE
v_myage NUMBER:=31;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child');
ELSE
DBMS_OUTPUT.PUT_LINE('I am not a child');
END IF;
END;
20
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF THEN ELSE Statement
•Remember that the statements in the THEN clause are
only executed if the condition returns TRUE
•In this case, the condition returns FALSE, so control
passes to the ELSE statement
20
DECLARE
v_myage NUMBER:=31;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child');
ELSE
DBMS_OUTPUT.PUT_LINE('I am not a child');
END IF;
END;
21
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF ELSIF ELSE Clause
•The IF statement now contains multiple ELSIF clauses
as well as an ELSE clause
•Notice that the ELSIF clauses add additional conditions
21
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF ELSIF ELSE Clause
22
DECLARE
v_myage NUMBER := 31;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child');
ELSIF v_myage < 20
THEN
DBMS_OUTPUT.PUT_LINE('I am young');
ELSIF v_myage < 30
THEN
DBMS_OUTPUT.PUT_LINE('I am in my twenties');
ELSIF v_myage < 40
THEN
DBMS_OUTPUT.PUT_LINE('I am in my thirties');
ELSE
DBMS_OUTPUT.PUT_LINE('I am mature');
END IF;
END;
22
23
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF ELSIF ELSE Clause
•As with the IF statement, each ELSIF condition is
followed by a THEN clause
•This is executed only if the ELSIF condition returns
TRUE
23
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF ELSIF ELSE Clause
24
DECLARE
v_myage NUMBER := 31;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child');
ELSIF v_myage < 20
THEN
DBMS_OUTPUT.PUT_LINE('I am young');
ELSIF v_myage < 30
THEN
DBMS_OUTPUT.PUT_LINE('I am in my twenties');
ELSIF v_myage < 40
THEN
DBMS_OUTPUT.PUT_LINE('I am in my thirties');
ELSE
DBMS_OUTPUT.PUT_LINE('I am mature');
END IF;
END;
24
The IF clause now contains multiple ELSIF clauses and an ELSE clause. Observe that the ELSIF
clauses have conditions, but the ELSE clause has no condition. The condition for ELSIF should be
followed by the THEN clause that is executed if the condition of the ELSIF clause returns TRUE.
When you have multiple ELSIF clauses, if the first condition is FALSE or NULL, the control shifts to
the next ELSIF clause.
25
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF ELSIF ELSE Clause
•When you have multiple clauses in the IF statement
and a condition is FALSE or NULL, control then passes
to the next clause
•Conditions are evaluated one by one
•If all conditions are FALSE or NULL, then the statements
in the ELSE clause are executed
25
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF ELSIF ELSE Clause
26
…IF v_myage < 11 THEN
DBMS_OUTPUT.PUT_LINE(' I am a child ');
ELSIF v_myage < 20 THEN
DBMS_OUTPUT.PUT_LINE(' I am young ');
ELSIF v_myage < 30 THEN
DBMS_OUTPUT.PUT_LINE(' I am in my twenties ');
ELSIF v_myage < 40 THEN
DBMS_OUTPUT.PUT_LINE(' I am in my thirties ');
ELSE
DBMS_OUTPUT.PUT_LINE(' I am always young ');
END IF;…
26
27
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF ELSIF ELSE Clause
•The final ELSE clause is optional
27
…IF v_myage < 11 THEN
DBMS_OUTPUT.PUT_LINE(' I am a child ');
ELSIF v_myage < 20 THEN
DBMS_OUTPUT.PUT_LINE(' I am young ');
ELSIF v_myage < 30 THEN
DBMS_OUTPUT.PUT_LINE(' I am in my twenties ');
ELSIF v_myage < 40 THEN
DBMS_OUTPUT.PUT_LINE(' I am in my thirties ');
ELSE
DBMS_OUTPUT.PUT_LINE(' I am always young ');
END IF;…
28
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statement with Multiple Expressions
•An IF statement can have multiple conditional
expressions related with logical operators, such as
AND, OR, and NOT
• This example uses the AND operator
•Therefore, it evaluates to TRUE only if both BOTH the
first name and age conditions are evaluated as TRUE
28
DECLARE
v_myage NUMBER := 31;
v_myfirstname VARCHAR2(11) := 'Christopher';
BEGIN
IF v_myfirstname ='Christopher' AND v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child named Christopher');
END IF;
END;
29
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
IF Statement with Multiple Expressions
•There is no limitation on the number of conditional
expressions that can be used
•However, these statements must be connected with
the appropriate logical operators
29
DECLARE
v_myage NUMBER := 31;
v_myfirstname VARCHAR2(11) := 'Christopher';
BEGIN
IF v_myfirstname ='Christopher' AND v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child named Christopher');
END IF;
END;
30
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
NULL Values in IF Statements
•In this example, the v_myage variable is declared but is
not initialized
•The condition in the IF statement returns NULL, which
is neither TRUE nor FALSE
•In such a case, the control goes to the ELSE statement
because, just NULL is not TRUE
30
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
NULL Values in IF Statements
31
DECLARE
v_myage NUMBER;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE('I am a child');
ELSE
DBMS_OUTPUT.PUT_LINE('I am not a child');
END IF;
END;
31
32
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Handling Nulls
•When working with nulls, you can avoid some common
mistakes by keeping in mind the following rules:
−Simple comparisons involving nulls always yield NULL
−Applying the logical operator NOT to a null yields NULL
−In conditional control statements, if a condition yields NULL,
it behaves just like a FALSE, and the associated sequence of
statements is not executed
32
33
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Handling Nulls Example
•In this example, you might expect the sequence of
statements to execute because a and b seem equal
•But, NULL is unknown, so we don't know if a and b are
equal
•The IF condition yields NULL and the THEN clause is
bypassed, with control going to the line following the
THEN clause
33
a := NULL;
b := NULL;
...
IF a = b THEN … -- yields NULL, not TRUE and the
sequence of statements is not executed
END IF;
34
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Guidelines for Using IF Statements
•Follow these guidelines when using IF statements:
−You can perform actions selectively when a specific condition
is being met
−When writing code, remember the spelling of the keywords:
• ELSIF is one word
• END IF is two words
34
35
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Guidelines for Using IF Statements
•If the controlling Boolean condition is TRUE, then the
associated sequence of statements is executed; if the
controlling Boolean condition is FALSE or NULL, then
the associated sequence of statements is passed over
•Any number of ELSIF clauses is permitted
•Indent the conditionally executed
statements for clarity
35
• CASE – An expression that determines a course of action based on conditions and can be used
outside of a PL/SQL block in a SQL statement.
• Condition – An expression with a TRUE or FALSE value that is used to make a decision.
• IF – Statement that enables PL/SQL to perform actions selectively based on conditions.
• LOOP– Control structures- Repetition statements that enable you to execute statements in a
PL/SQL block repeatedly.
36
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Terminology
•Key terms used in this lesson included:
−CASE
−Condition
−IF
−LOOP
36
37
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-1
Conditional Control: IF State
Summary
•In this lesson, you should have learned how to:
−Describe a use for conditional control structures
−List the types of conditional control structures
−Construct and use an IF statement
−Construct and use an IF-THEN-ELSE statement
−Create PL/SQL to handle the null condition in IF statements
37
1
2
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
Database Programming with
PL/SQL
4-2
Conditional Control: Case Statements
3
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Objectives
•This lesson covers the following objectives:
−Construct and use CASE statements in PL/SQL
−Construct and use CASE expressions in PL/SQL
−Include the correct syntax to handle null conditions in PL/SQL
CASE statements
−Include the correct syntax to handle Boolean conditions in
PL/SQL IF and CASE statements
3
4
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Purpose
•In this lesson, you learn how to use CASE statements
and CASE expressions in a PL/SQL block
•CASE STATEMENTS are similar to IF statements, but are
often easier to write and easier to read
•CASE EXPRESSIONS work like functions to return one
value from a number of values into a variable
4
5
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Using a CASE Statement
•Look at this IF statement. What do you notice?
•All the conditions test the same variable v_numvar
•And the coding is very repetitive: v_numvar is coded
many times
5
DECLARE
v_numvar NUMBER;
BEGIN
...
IF v_numvar = 5 THEN statement_1; statement_2;
ELSIF v_numvar = 10 THEN statement_3;
ELSIF v_numvar = 12 THEN statement_4; statement_5;
ELSIF v_numvar = 27 THEN statement_6;
ELSIF v_numvar ... – and so on
ELSE statement_15;
END IF; ...
END;
The WHEN clauses, “WHEN 5,” “WHEN 10,” “WHEN 12,” etc. mean: WHEN v_numvar is equal to 5,
and WHEN v_numvar is equal to 10, etc.
6
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Using a CASE Statement
•Here is the same logic, but using a CASE statement
•It is much easier to read. v_numvar is written only
once
6
DECLARE
v_numvar NUMBER;
BEGIN
...
CASE v_numvar
WHEN 5 THEN statement_1; statement_2;
WHEN 10 THEN statement_3;
WHEN 12 THEN statement_4; statement_5;
WHEN 27 THEN statement_6;
WHEN ... – and so on
ELSE statement_15;
END CASE;
...
END;
7
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
CASE Statements: An Example
•A simple example to demonstrate the CASE logic
7
DECLARE
v_num NUMBER := 15;
v_txt VARCHAR2(50);
BEGIN
CASE v_num
WHEN 20 THEN v_txt := 'number equals 20';
WHEN 17 THEN v_txt := 'number equals 17';
WHEN 15 THEN v_txt := 'number equals 15';
WHEN 13 THEN v_txt := 'number equals 13';
WHEN 10 THEN v_txt := 'number equals 10';
ELSE v_txt := 'some other number';
END CASE;
DBMS_OUTPUT.PUT_LINE(v_txt);
END;
The same logic from above, rewritten using an IF statement:
DECLARE
v_num NUMBER := 15;
v_txt VARCHAR2(50);
BEGIN
IF v_num > 20 THEN v_txt := 'greater than 20';
ELSIF v_num > 15 THEN v_txt := 'greater than 15';
ELSE v_txt := 'less than 16';
END IF;
DBMS_OUTPUT.PUT_LINE(v_txt);
END;
8
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Searched CASE Statements
•You can use CASE statements to test for non-equality
conditions such as <, >, >=, etc.
•These are called searched CASE statements
•The syntax is virtually identical to an equivalent IF
statement
8
DECLARE
v_num NUMBER := 15;
v_txt VARCHAR2(50);
BEGIN
CASE
WHEN v_num > 20 THEN v_txt := 'greater than 20';
WHEN v_num > 15 THEN v_txt := 'greater than 15';
ELSE v_txt := 'less than 16';
END CASE;
DBMS_OUTPUT.PUT_LINE(v_txt);
END;
9
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Using a CASE Expression
•You want to assign a value to one variable that
depends on the value in another variable
•Look at this IF statement
•Again, the coding is very repetitive
9
DECLARE
v_out_var VARCHAR2(15);
v_in_var NUMBER;
BEGIN
...
IF v_in_var = 1 THEN v_out_var := 'Low value';
ELSIF v_in_var = 50 THEN v_out_var := 'Middle value';
ELSIF v_in_var = 99 THEN v_out_var := 'High value';
ELSE v_out_var := 'Other value';
END IF;
...
END;
10
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Using a CASE Expression
•Here is the same logic, but using a CASE expression:
10
DECLARE
v_out_var VARCHAR2(15);
v_in_var NUMBER;
BEGIN
...
v_out_var := CASE v_in_var
WHEN 1 THEN 'Low value'
WHEN 50 THEN 'Middle value'
WHEN 99 THEN 'High value'
ELSE 'Other value'
END;
...
END;
11
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
CASE Expression Syntax
•A CASE expression is different from a CASE statement
because it selects one of a number of results and
assigns it to a variable
•A CASE expression ends with END not END CASE
•In the syntax, expressionN can be a literal value or an
expression such as (v_other_var * 2)
11
variable_name :=
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
[ELSE resultN+1]
END;
Answer:
Grade: C
Appraisal: Good
Statement processed.
12
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
CASE Expression Example
•What would be the result of this code if v_grade was
initialized as "C" instead of "A"
12
DECLARE
v_grade CHAR(1) := 'A';
v_appraisal VARCHAR2(20);
BEGIN
v_appraisal :=
CASE v_grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Very Good'
WHEN 'C' THEN 'Good'
ELSE 'No such grade'
END;
DBMS_OUTPUT.PUT_LINE('Grade: ' || v_grade ||
' Appraisal: ' || v_appraisal);
END;
RESULT:
Grade: A
Appraisal: Excellent
Statement processed.
Answer: "Same value" will be displayed. Remember, read the highlighted WHEN clause as, "When
v_in_var is equal to v_in_var, then assign "Same value" to v_out_var and skip to the line following
the CASE expression end." Since v_in_var is equal to itself, the code will display the phrase, "Same
value."
13
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
CASE Expression: A Second Example
•Determine what will be displayed when this block is
executed:
13
DECLARE
v_out_var VARCHAR2(15);
v_in_var NUMBER := 20;
BEGIN
v_out_var :=
CASE v_in_var
WHEN 1 THEN 'Low value'
WHEN v_in_var THEN 'Same value'
WHEN 20 THEN 'Middle value'
ELSE 'Other value'
END;
DBMS_OUTPUT.PUT_LINE(v_out_var);
END;
Searched CASE expressions are more flexible, allowing non-equality conditions (and compound
conditions) to be tested and different variables to be used in different WHEN clauses.
14
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Searched CASE Expression Syntax
• PL/SQL also provides a searched CASE expression, which
has the following form:
• A searched CASE expression has no selector
• Also, its WHEN clauses contain search conditions that yield
a Boolean value, not expressions that can yield a value of
any type
14
variable_name := CASE
WHEN search_condition1 THEN result1
WHEN search_condition2 THEN result2
...
WHEN search_conditionN THEN resultN
[ELSE resultN+1]
END;
We could have used a non-searched CASE expression. The example in the slide could be written
as:
v_appraisal :=
CASE v_ grade
WHEN ‘A’ THEN ‘Excellent’
WHEN ‘B’ THEN ‘Good’
WHEN ‘C’ THEN ‘Good’
ELSE ‘No such grade’
END;
15
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Searched CASE Expressions: An Example
•Searched CASE expressions allow non-equality
conditions, compound conditions, and different
variables to be used in different WHEN clauses
15
DECLARE
v_grade CHAR(1) := 'A';
v_appraisal VARCHAR2(20);
BEGIN
v_appraisal :=
CASE -- no selector here
WHEN v_grade = 'A' THEN 'Excellent'
WHEN v_grade IN ('B','C') THEN 'Good'
ELSE 'No such grade'
END;
DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade ||
' Appraisal ' || v_appraisal);
END;
CASE expressions are actually functions, which always return exactly one value.
A common, built-in function is SYSDATE. Just like a CASE expression, SYSDATE assigns one value to
a variable.
v_date := SYSDATE;
16
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
How are CASE Expressions Different From CASE
Statements?
•They are different because:
−CASE expressions return a value into a variable
−CASE expressions end with END;
−A CASE expression is a single PL/SQL statement
16
DECLARE
v_grade CHAR(1) := 'A';
v_appraisal VARCHAR2(20);
BEGIN
v_appraisal :=
CASE
WHEN v_grade = 'A' THEN 'Excellent'
WHEN v_grade IN ('B','C') THEN 'Good'
ELSE 'No such grade'
END;
DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade || ' Appraisal '
|| v_appraisal);
END;
A CASE expression has only one terminating semicolon at the END;, while a CASE statement has a
semicolon after each executable statement in a WHEN clause.
17
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
How are CASE Expressions Different From CASE
Statements?
•CASE statements evaluate conditions and perform
actions
•A CASE statement can contain many PL/SQL statements
•CASE statements end with END CASE;
17
DECLARE
v_grade CHAR(1) := 'A';
BEGIN
CASE
WHEN v_grade = 'A' THEN
DBMS_OUTPUT.PUT_LINE ('Excellent');
WHEN v_grade IN ('B','C') THEN
DBMS_OUTPUT.PUT_LINE ('Good');
ELSE
DBMS_OUTPUT.PUT_LINE('No such grade');
END CASE;
END;
You can build a simple Boolean condition by combining number, character, or date expressions
with comparison operators.
You can build a complex Boolean condition by combining simple Boolean conditions with the
logical operators AND, OR, and NOT. The logical operators are used to check the Boolean variable
values and return TRUE, FALSE, or NULL.
Note: The negation of NULL (NOT NULL) results in a null value because null values are
indeterminate.
18
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Logic Tables
•When using IF and CASE statements you often need to
combine conditions using AND, OR, and NOT
•The following Logic Table displays the results of all
possible combinations of two conditions
•Example: TRUE and FALSE is FALSE
18
AND TRUE FALSE NULL OR TRUE FALSE NULL NOT
TRUE TRUE
Ex.
FALSE
NULL TRUE TRUE TRUE TRUE TRUE FALSE
FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL FALSE TRUE
NULL NULL FALSE NULL NULL TRUE NULL NULL NULL NULL
The AND Logic Table on the previous slide can help you evaluate the possibilities for the Boolean
condition in this slide.
Answers:
1. TRUE
2. FALSE
3. NULL
4. FALSE
19
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Boolean Conditions
•What is the value of v_flag in each case?
19
v_flag := v_reorder_flag AND v_available_flag;
V_REORDER_FLAG V_AVAILABLE_FLAG V_FLAG
TRUE TRUE 1. _____
TRUE FALSE 2. _____
NULL TRUE 3. _____
NULL FALSE 4. _____
• CASE expression – An expression that selects a result and returns it into a variable.
• CASE statement – A block of code that performs actions based on conditional tests.
• Logic Tables – Shows the results of all possible combinations of two conditions.
20
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Terminology
•Key terms used in this lesson included:
−CASE expression
−CASE statement
−Logic tables
20
21
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-2
Conditional Control: Case Statements
Summary
•In this lesson, you should have learned how to:
−Construct and use CASE statements in PL/SQL
−Construct and use CASE expressions in PL/SQL
−Include the correct syntax to handle null conditions in PL/SQL
CASE statements
−Include the correct syntax to handle Boolean conditions in
PL/SQL IF and CASE statements
21
22
1
2
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
Database Programming with
PL/SQL
4-3
Iterative Control: Basic Loops
3
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Objectives
•This lesson covers the following objectives:
−Describe the need for LOOP statements in PL/SQL
−Recognize different types of LOOP statements
−Create PL/SQL containing a basic loop and an EXIT statement
−Create PL/SQL containing a basic loop and an EXIT statement
with conditional termination
3
4
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Purpose
•Looping constructs are the second type of control
structure
•Loops are mainly used to execute statements
repeatedly until an EXIT condition is reached
•PL/SQL provides three ways to structure loops to
repeat a statement or a sequence of statements
multiple times
•These are basic loops, FOR loops, and WHILE loops
•This lesson introduces the three loop types and
discusses basic loops in greater detail
4
WARNING:
When a user executes a PL/SQL block in APEX that contains an infinite loop, there is no way for the
user to stop the loop. It can only be stopped by the DBA who oversees the Academy database. If
the loop does not contain DML statements, closing the browser window and reopening it will
allow the user to continue coding. If the block contains a FOR UPDATE clause, the affected table(s)
will remain locked until released by the DBA, which may take a day or more.
Be careful executing loops. All loops required by this course should have some type of limiting
condition. NO infinite loops are required as part of this course.
Each loop is structured for a specific purpose. These loops are used to write code to handle all
situations (problems). Loops can repeat one statement, a group of statements, and/or a block.
Loops have a scope and loop variables have a life.
5
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Iterative Control: LOOP Statements
•Loops repeat a statement or a sequence of statements
multiple times
•PL/SQL provides the following types of loops:
−Basic loops that perform repetitive actions without overall
conditions
−FOR loops that perform iterative actions based on a counter
−WHILE loops that perform repetitive actions based on a
condition
5
6
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Basic Loops
•The simplest form of a LOOP statement is the basic
loop, which encloses a sequence of statements
between the keywords LOOP and END LOOP
•Use the basic loop when the statements inside the
loop must execute at least once
6
7
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Basic Loops Exit
•Each time the flow of execution reaches the END LOOP
statement, control is passed to the corresponding
LOOP statement that introduced it
•A basic loop allows the execution of its statements at
least once, even if the EXIT condition is already met
upon entering the loop
•Without the EXIT statement, the loop would never end
(an infinite loop)
7
BEGIN
LOOP
statements;
EXIT [WHEN condition];
END LOOP;
END;
8
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Basic Loops Simple Example
•In this example, no data is processed
•We simply display the loop counter each time we
repeat the loop
8
DECLARE
v_counter NUMBER(2) := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Loop execution #' || v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 5;
END LOOP;
END;
9
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Basic Loops More Complex Example
•In this example, three new location IDs for Montreal,
Canada, are inserted in the LOCATIONS table
9
DECLARE
v_loc_id locations.location_id%TYPE;
v_counter NUMBER(2) := 1;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = 2;
LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), 'Montreal', 2);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 3;
END LOOP;
END;
10
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Basic Loops EXIT Statement
•You can use the EXIT statement to terminate a loop
and pass control to the next statement after the END
LOOP statement
•You can issue EXIT as an action within an IF statement
10
DECLARE
v_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter is ' || v_counter);
v_counter := v_counter + 1;
IF v_counter > 10 THEN EXIT;
END IF;
END LOOP;
END;
11
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Basic Loop EXIT Statement Rules
•Rules:
−The EXIT statement must be placed inside a loop
−If the EXIT condition is placed at the top of the loop (before
any of the other executable statements) and that condition is
initially true, then the loop exits and the other statements in
the loop never execute
−A basic loop can contain multiple EXIT statements
11
The statement, EXIT WHEN v_counter > 10, is logically identical to:
IF v_counter > 10 THEN EXIT;
END IF;
However, in PL/SQL, the EXIT WHEN statement is the appropriate syntax. From a programmer's
perspective, it is the more elegant solution.
12
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Basic Loop EXIT WHEN Statement
•Although the IF…THEN EXIT works to end a loop, the
correct way to end a basic loop is with the EXIT WHEN
statement
•If the WHEN clause evaluates to TRUE, the loop ends
and control passes to the next statement following
END LOOP
12
DECLARE
v_counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter is ' || v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;
END LOOP;
END;
• Basic Loop – A sequence of statements between the keywords LOOP and END LOOP; the
statements must execute at least once.
• Counter – A counter is a variable that programmers use to keep track of the number of times a
loop executes (or repeats). When a specific value is reached, it triggers the execution of the
EXIT command which stops the loop from repeating, passing control to the first command
following the END LOOP command.
• END LOOP – A PL/SQL command that marks the end of the statements within a loop and
returns control to the corresponding LOOP statement that introduced it (the loop begins again).
• EXIT – Statement to terminate a loop.
• LOOP – A PL/SQL command that marks the beginning of the statements within a loop.
13
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Terminology
•Key terms used in this lesson included:
−Basic Loop
−Counter
−END LOOP
−EXIT
−LOOP
13
14
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-3
Iterative Control: Basic Loops
Summary
•In this lesson, you should have learned how to:
−Describe the need for LOOP statements in PL/SQL
−Recognize different types of LOOP statements
−Create PL/SQL containing a basic loop and an EXIT statement
−Create PL/SQL containing a basic loop and an EXIT statement
with conditional termination
14
15
1
2
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
Database Programming with
PL/SQL
4-4
Iterative Control: WHILE and FOR Loops
3
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
Objectives
•This lesson covers the following objectives:
−Construct and use the WHILE looping construct in PL/SQL
−Construct and use the FOR looping construct in PL/SQL
−Describe when a WHILE loop is used in PL/SQL
−Describe when a FOR loop is used in PL/SQL
3
4
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
Purpose
•The previous lesson discussed the basic loop, which
allows the statements inside the loop to execute at
least once
•This lesson introduces the WHILE loop and FOR loop
•The WHILE loop is a looping construct which requires
the controlling condition be evaluated at the start of
each iteration
•The FOR loop should be used if the number of
iterations is known
4
Since the WHILE loop depends on a condition and is not fixed, use the WHILE loop when you don’t
know in advance the number of times a loop must execute.
5
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
WHILE Loops
•You can use the WHILE loop to repeat a sequence of
statements until the controlling condition is no longer
TRUE
•The condition is evaluated at the start of each iteration
•The loop terminates when the condition is FALSE or
NULL
•If the condition is FALSE or NULL at the initial execution
of the loop, then no iterations are performed
5
WHILE condition LOOP
statement1;
statement2;
. . .
END LOOP;
6
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
WHILE Loops
•In the syntax:
•Condition is a Boolean variable or expression (TRUE,
FALSE, or NULL)
•Statement can be one or more PL/SQL or SQL
statements
6
WHILE condition LOOP
statement1;
statement2;
. . .
END LOOP;
7
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
WHILE
•In the syntax:
•If the variables involved in the conditions do not
change during the body of the loop, then the condition
remains TRUE and the loop does not terminate
•Note: If the condition yields NULL, then the loop is
bypassed and control passes to the statement that
follows the loop
7
WHILE condition LOOP
statement1;
statement2;
. . .
END LOOP;
Notice the similarities and differences to the basic loop from the previous lesson:
DECLARE
v_loc_id locations.location_id%TYPE;
v_counter NUMBER(2) := 1;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = 'CA';
LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), 'Montreal', 'CA');
v_counter := v_counter + 1;
EXIT WHEN v_counter > 3;
END LOOP;
8
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
WHILE Loops
•In this example, three new location IDs for Montreal,
Canada, are inserted in the LOCATIONS table
•The counter is explicitly declared in this example
8
DECLARE
v_loc_id locations.location_id%TYPE;
v_counter NUMBER := 1;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = 2;
WHILE v_counter <= 3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), 'Montreal', 2);
v_counter := v_counter + 1;
END LOOP;
END;
END;
8
9
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
WHILE Loops
•With each iteration through the WHILE loop, a counter
(v_counter) is incremented
•If the number of iterations is less than or equal to the
number 3, then the code within the loop is executed
and a row is inserted into the locations table
9
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
WHILE Loops
10
DECLARE
v_loc_id locations.location_id%TYPE;
v_counter NUMBER := 1;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = 2;
WHILE v_counter <= 3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), 'Montreal', 2);
v_counter := v_counter + 1;
END LOOP;
END;
10
11
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
WHILE Loops
•After the counter exceeds the number of new locations
for this city and country, the condition that controls the
loop evaluates to FALSE and the loop is terminated
11
DECLARE
v_loc_id locations.location_id%TYPE;
v_counter NUMBER := 1;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = 2;
WHILE v_counter <= 3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), 'Montreal', 2);
v_counter := v_counter + 1;
END LOOP;
END;
12
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
FOR Loops Described
•FOR loops have the same general structure as the basic
loop
•In addition, they have a control statement before the
LOOP keyword to set the number of iterations that
PL/SQL performs
12
FOR counter IN [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
. . .
END LOOP;
13
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
FOR Loop Rules
•FOR loop rules:
−Use a FOR loop to shortcut the test for the number of
iterations
−Do not declare the counter; it is declared implicitly
−lower_bound .. upper_bound is the required syntax
13
FOR counter IN [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
. . .
END LOOP;
14
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
FOR Loops Syntax
•Counter is an implicitly declared integer whose value
automatically increases or decreases (decreases if the
REVERSE keyword is used) by 1 on each iteration of the
loop until the upper or lower bound is reached
•REVERSE causes the counter to decrement with each
iteration from the upper bound to the lower bound
• (Note that the lower bound is referenced first)
14
FOR counter IN [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
. . .
END LOOP;
Note these examples for controlling the counter through the FOR loop:
FOR i IN 1..5 LOOP …; -- successive values 1,2,3,4,5
FOR i IN REVERSE 1..5 LOOP …; -- successive values 5,4,3,2,1
FOR i IN REVERSE 5..1 LOOP …; -- will cause an error.
15
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
FOR Loops Syntax
•lower_bound specifies the lower bound for the range
of counter values
•upper_bound specifies the upper bound for the range
of counter values
15
FOR counter IN [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
. . .
END LOOP;
16
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
FOR Loop Example
•You have already learned how to insert three new
locations for the country code CA and the city
Montreal by using the simple LOOP and the WHILE
loop
•The next slide shows you how to achieve the same by
using the FOR loop
16
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
FOR Loop Example
17
DECLARE
v_loc_id locations.location_id%TYPE;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = 2;
FOR i IN 1..3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + i), 'Montreal', 2);
END LOOP;
END;
17
18
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
FOR Loop Guidelines
•FOR loops are a common structure of programming
languages
•A FOR loop is used within the code when the beginning
and ending value of the loop is known
•Reference the counter only within the loop; its scope
does not extend outside the loop
•Do not reference the counter as the target of an
assignment
•Neither loop bound (lower or upper) should be NULL
18
19
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
FOR Loop Expression Example
•While writing a FOR loop, the lower and upper bounds
of a LOOP statement do not need to be numeric literals
•They can be expressions that convert to numeric values
19
DECLARE
v_lower NUMBER := 1;
v_upper NUMBER := 100;
BEGIN
FOR i IN v_lower..v_upper LOOP
...
END LOOP;
END;
Note: All loops allow the use of an EXIT WHEN condition allowing the loop to terminate before the
WHILE condition is false or the upper bound of the FOR loop is reached
Remember that all the variables used within the loop block have a scope. The specific loop needed
is determined by the problem being solved.
20
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
Guidelines For When to Use Loops
•Use the basic loop when the statements inside the
loop must execute at least once
•Use the WHILE loop if the condition has to be
evaluated at the start of each iteration
•Use a FOR loop if the number of iterations is known
20
• FOR Loop – Repeats a sequence of statements until a set number of iterations are fulfilled.
• Lower Bound – The FOR loop syntax that specifies the lower bound for the range of counter
values.
• REVERSE – A PL/SQL command that causes the FOR loop counter to decrement with each
iteration from the upper bound to the lower bound.
• Upper Bound – The FOR loop syntax that specifies the upper bound for the range of counter
values.
• WHILE Loop – Repeats a sequence of statements until the controlling condition is no longer
TRUE.
21
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
Terminology
•Key terms used in this lesson included:
−FOR loops
−Lower Bound
−REVERSE
−Upper Bound
−WHILE loops
21
22
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-4
Iterative Control: WHILE and FOR Loops
Summary
•In this lesson, you should have learned how to:
−Construct and use the WHILE looping construct in PL/SQL
−Construct and use the FOR looping construct in PL/SQL
−Describe when a WHILE loop is used in PL/SQL
−Describe when a FOR loop is used in PL/SQL
22
23
1
2
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
Database Programming with
PL/SQL
4-5
Iterative Control: Nested Loops
3
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Objectives
•This lesson covers the following objectives:
−Construct and execute PL/SQL using nested loops
−Label loops and use the labels in EXIT statements
−Evaluate a nested loop construct and identify the exit point
3
4
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Purpose
•You’ve learned about looping constructs in PL/SQL
•This lesson discusses how you can nest loops to
multiple levels
•You can nest FOR, WHILE, and basic loops within one
another
4
The slide example shows a FOR loop nested inside another FOR loop. But (for example) we could
nest a WHILE loop inside a FOR loop; or a FOR loop inside a basic loop; or etc. All combinations
are allowed.
5
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Nested Loop Example
•In PL/SQL, you can nest loops to multiple levels
•You can nest FOR, WHILE, and basic loops within one
another
5
BEGIN
FOR v_outerloop IN 1..3 LOOP
FOR v_innerloop IN REVERSE 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Outer loop is: ' ||
v_outerloop ||
' and inner loop is: ' ||
v_innerloop);
END LOOP;
END LOOP;
END;
Answer : We will discuss loop labels in the next slides to answer this question.
Notice that when V_INNER_DONE = 'YES', PL/SQL exits the inner loop but the outer loop continues
executing.
6
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Nested Loops
•This example contains EXIT conditions in nested basic
loops
•What if you want to exit from the outer loop at step A?
6
DECLARE
v_outer_done CHAR(3) := 'NO';
v_inner_done CHAR(3) := 'NO';
BEGIN
LOOP -- outer loop
...
LOOP -- inner loop
...
... -- step A
EXIT WHEN v_inner_done = 'YES';
...
END LOOP;
...
EXIT WHEN v_outer_done = 'YES';
...
END LOOP;
END;
7
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Loop Labels
•Loop labels are required in this example in order to exit
an outer loop from within an inner loop
7
DECLARE
...
BEGIN
<<outer_loop>>
LOOP -- outer loop
...
<<inner_loop>>
LOOP -- inner loop
EXIT outer_loop WHEN ... -- exits both loops
EXIT WHEN v_inner_done = 'YES';
...
END LOOP;
...
EXIT WHEN v_outer_done = 'YES'; ...
END LOOP;
END;
8
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Loop Labels
•Loop label names follow the same rules as other
identifiers
•A label is placed before a statement, either on the
same line or on a separate line
•In FOR or WHILE loops, place the label before FOR or
WHILE within label delimiters (<<label>>)
•If the loop is labeled, the label name can optionally be
included after the END LOOP statement for clarity
8
The loop labels are not required in this example, but they do make the code more readable.
9
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Loop Labels
•Label basic loops by placing the label before the word
LOOP within label delimiters (<<label>>)
9
DECLARE
v_outerloop PLS_INTEGER := 0;
v_innerloop PLS_INTEGER := 5;
BEGIN
<<outer_loop>>
LOOP
v_outerloop := v_outerloop + 1;
v_innerloop := 5;
EXIT WHEN v_outerloop > 3;
<<inner_loop>>
LOOP
DBMS_OUTPUT.PUT_LINE('Outer loop is: ' || v_outerloop ||
' and inner loop is: ' || v_innerloop);
v_innerloop := v_innerloop - 1;
EXIT WHEN v_innerloop = 0;
END LOOP inner_loop;
END LOOP outer_loop;
END;
10
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Nested Loops and Labels
•In this example, there are two loops
•The outer loop is identified by the label
<<outer_loop>>, and the inner loop is identified by the
label <<inner_loop>>
•We reference the outer loop in the EXIT statement
from within the
inner_loop
10
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Nested Loops and Labels
11
...BEGIN
<<outer_loop>>
LOOP
v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;
<<inner_loop>>
LOOP ...
EXIT outer_loop WHEN v_total_done = 'YES';
-- Leave both loops
EXIT WHEN v_inner_done = 'YES';
-- Leave inner loop only ...
END LOOP inner_loop; ...
END LOOP outer_loop;
END;
11
• Label Delimiters – Characters placed before (<<) and after (>>) a loop label to identify the label
as a loop label.
• Loop Label – A loop identifier that is required in order to exit an outer loop from within an inner
loop.
12
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Terminology
•Key terms used in this lesson included:
−Label Delimiters
−Loop Label
12
13
Copyright © 2020, Oracle and/or its affiliates. All rights reserved.
PLSQL 4-5
Iterative Control: Nested Loops
Summary
•In this lesson, you should have learned how to:
−Construct and execute PL/SQL using nested loops
−Label loops and use the labels in EXIT statements
−Evaluate a nested loop construct and identify the exit point
13
14

More Related Content

What's hot

Oracle sql & plsql
Oracle sql & plsqlOracle sql & plsql
Oracle sql & plsqlSid Xing
 
10g plsql slide
10g plsql slide10g plsql slide
10g plsql slideTanu_Manu
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Proceduresrehaniltifat
 
Introduction to PL/SQL
Introduction to PL/SQLIntroduction to PL/SQL
Introduction to PL/SQLKailash N
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesSmitha Padmanabhan
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsSalman Memon
 
Displaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseDisplaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseSalman Memon
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQLPooja Dixit
 
Forall & bulk binds
Forall & bulk bindsForall & bulk binds
Forall & bulk bindsNawaz Sk
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group FunctionsSalman Memon
 
122 sql for-beginners
122 sql for-beginners122 sql for-beginners
122 sql for-beginnerssuzzanj1990
 
Producing Readable Output with iSQL*Plus - Oracle Data Base
Producing Readable Output with iSQL*Plus - Oracle Data BaseProducing Readable Output with iSQL*Plus - Oracle Data Base
Producing Readable Output with iSQL*Plus - Oracle Data BaseSalman Memon
 

What's hot (18)

Oracle sql & plsql
Oracle sql & plsqlOracle sql & plsql
Oracle sql & plsql
 
Les01
Les01Les01
Les01
 
10g plsql slide
10g plsql slide10g plsql slide
10g plsql slide
 
DBMS 2011
DBMS 2011DBMS 2011
DBMS 2011
 
4. plsql
4. plsql4. plsql
4. plsql
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
 
plsql Les09
 plsql Les09 plsql Les09
plsql Les09
 
Introduction to PL/SQL
Introduction to PL/SQLIntroduction to PL/SQL
Introduction to PL/SQL
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 
SQL- Introduction to PL/SQL
SQL- Introduction to  PL/SQLSQL- Introduction to  PL/SQL
SQL- Introduction to PL/SQL
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
 
Displaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data BaseDisplaying Data from Multiple Tables - Oracle Data Base
Displaying Data from Multiple Tables - Oracle Data Base
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
Forall & bulk binds
Forall & bulk bindsForall & bulk binds
Forall & bulk binds
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
122 sql for-beginners
122 sql for-beginners122 sql for-beginners
122 sql for-beginners
 
Producing Readable Output with iSQL*Plus - Oracle Data Base
Producing Readable Output with iSQL*Plus - Oracle Data BaseProducing Readable Output with iSQL*Plus - Oracle Data Base
Producing Readable Output with iSQL*Plus - Oracle Data Base
 

Similar to PL/SQL CONDICIONALES Y CICLOS

Les19[1]Writing Control Structures
Les19[1]Writing Control StructuresLes19[1]Writing Control Structures
Les19[1]Writing Control Structuressiavosh kaviani
 
Take Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerTake Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerSteven Feuerstein
 
Oracle pl/sql control statments
Oracle pl/sql control statmentsOracle pl/sql control statments
Oracle pl/sql control statmentsTayba Bashir
 
Advanced_SQL_ISASasASasaASnjection (1).ppt
Advanced_SQL_ISASasASasaASnjection (1).pptAdvanced_SQL_ISASasASasaASnjection (1).ppt
Advanced_SQL_ISASasASasaASnjection (1).pptssuserde23af
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4Cso gaddis java_chapter4
Cso gaddis java_chapter4mlrbrown
 
Lecture 2.3.26_Conditional Control Structure.pptx
Lecture 2.3.26_Conditional Control Structure.pptxLecture 2.3.26_Conditional Control Structure.pptx
Lecture 2.3.26_Conditional Control Structure.pptxShivam481778
 
Week03
Week03Week03
Week03hccit
 
STATEMENT’S AND LOOP’S
STATEMENT’S AND LOOP’SSTATEMENT’S AND LOOP’S
STATEMENT’S AND LOOP’SBilalAhmed802
 
Week04
Week04Week04
Week04hccit
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#Prasanna Kumar SM
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Trainingsuresh
 
Satyapriya rajguru: Every day, in one way or another.
Satyapriya  rajguru:  Every day, in one way or another.Satyapriya  rajguru:  Every day, in one way or another.
Satyapriya rajguru: Every day, in one way or another.Satyapriya Rajguru
 
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingTurbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingSteven Feuerstein
 

Similar to PL/SQL CONDICIONALES Y CICLOS (20)

PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
Les19[1]Writing Control Structures
Les19[1]Writing Control StructuresLes19[1]Writing Control Structures
Les19[1]Writing Control Structures
 
D34010.pdf
D34010.pdfD34010.pdf
D34010.pdf
 
Take Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerTake Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL Compiler
 
Oracle pl/sql control statments
Oracle pl/sql control statmentsOracle pl/sql control statments
Oracle pl/sql control statments
 
Advanced_SQL_ISASasASasaASnjection (1).ppt
Advanced_SQL_ISASasASasaASnjection (1).pptAdvanced_SQL_ISASasASasaASnjection (1).ppt
Advanced_SQL_ISASasASasaASnjection (1).ppt
 
Loop structures
Loop structuresLoop structures
Loop structures
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4Cso gaddis java_chapter4
Cso gaddis java_chapter4
 
Lecture 2.3.26_Conditional Control Structure.pptx
Lecture 2.3.26_Conditional Control Structure.pptxLecture 2.3.26_Conditional Control Structure.pptx
Lecture 2.3.26_Conditional Control Structure.pptx
 
Week03
Week03Week03
Week03
 
STATEMENT’S AND LOOP’S
STATEMENT’S AND LOOP’SSTATEMENT’S AND LOOP’S
STATEMENT’S AND LOOP’S
 
Week04
Week04Week04
Week04
 
Plsql 9i vol2
Plsql 9i vol2Plsql 9i vol2
Plsql 9i vol2
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#
 
Pl sql-ch1
Pl sql-ch1Pl sql-ch1
Pl sql-ch1
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
 
Pl sql
Pl sqlPl sql
Pl sql
 
Advanced sql injection 2
Advanced sql injection 2Advanced sql injection 2
Advanced sql injection 2
 
Satyapriya rajguru: Every day, in one way or another.
Satyapriya  rajguru:  Every day, in one way or another.Satyapriya  rajguru:  Every day, in one way or another.
Satyapriya rajguru: Every day, in one way or another.
 
Turbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk ProcessingTurbocharge SQL Performance in PL/SQL with Bulk Processing
Turbocharge SQL Performance in PL/SQL with Bulk Processing
 

More from Richard Eliseo Mendoza Gafaro

PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 3
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 3PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 3
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 3Richard Eliseo Mendoza Gafaro
 
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 2
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 2PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 2
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 2Richard Eliseo Mendoza Gafaro
 
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 4
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 4PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 4
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 4Richard Eliseo Mendoza Gafaro
 
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 1
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 1PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 1
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 1Richard Eliseo Mendoza Gafaro
 
PARCIAL 2 SISTEMAS OPERATIVOS - BD MYSQL EN ORACLE OCI
PARCIAL 2 SISTEMAS OPERATIVOS - BD MYSQL EN ORACLE OCIPARCIAL 2 SISTEMAS OPERATIVOS - BD MYSQL EN ORACLE OCI
PARCIAL 2 SISTEMAS OPERATIVOS - BD MYSQL EN ORACLE OCIRichard Eliseo Mendoza Gafaro
 

More from Richard Eliseo Mendoza Gafaro (20)

CUESTIONARIO REDES TELEMATICAS CISCO, HPE Y HUAWEI
CUESTIONARIO REDES TELEMATICAS CISCO, HPE Y HUAWEICUESTIONARIO REDES TELEMATICAS CISCO, HPE Y HUAWEI
CUESTIONARIO REDES TELEMATICAS CISCO, HPE Y HUAWEI
 
Material_para_Estudiante_DMPC_V012022A_SP_1
Material_para_Estudiante_DMPC_V012022A_SP_1Material_para_Estudiante_DMPC_V012022A_SP_1
Material_para_Estudiante_DMPC_V012022A_SP_1
 
MANUAL DE ORACLE AUTONOMOUS DATABASE
MANUAL DE ORACLE AUTONOMOUS DATABASEMANUAL DE ORACLE AUTONOMOUS DATABASE
MANUAL DE ORACLE AUTONOMOUS DATABASE
 
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 3
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 3PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 3
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 3
 
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 2
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 2PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 2
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 2
 
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 4
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 4PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 4
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 4
 
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 1
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 1PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 1
PARCIAL 2 PLATAFORMAS Y SOPORTES MULTIMEDIA 2023-2-VARIANTE 1
 
PARCIAL 2 SISTEMAS OPERATIVOS - BD MYSQL EN ORACLE OCI
PARCIAL 2 SISTEMAS OPERATIVOS - BD MYSQL EN ORACLE OCIPARCIAL 2 SISTEMAS OPERATIVOS - BD MYSQL EN ORACLE OCI
PARCIAL 2 SISTEMAS OPERATIVOS - BD MYSQL EN ORACLE OCI
 
PARCIAL 2 DESARROLLO DE INTERFACES UI UX
PARCIAL 2 DESARROLLO DE INTERFACES UI UXPARCIAL 2 DESARROLLO DE INTERFACES UI UX
PARCIAL 2 DESARROLLO DE INTERFACES UI UX
 
Explicación cadena de valor
Explicación cadena de valorExplicación cadena de valor
Explicación cadena de valor
 
MANUAL DESPLIEGUE SERVIDOR WEB
MANUAL DESPLIEGUE SERVIDOR WEBMANUAL DESPLIEGUE SERVIDOR WEB
MANUAL DESPLIEGUE SERVIDOR WEB
 
MANUAL DE DESPLIEGUE BASE DE DATOS CON WORKBENCH
MANUAL DE DESPLIEGUE BASE DE DATOS CON WORKBENCHMANUAL DE DESPLIEGUE BASE DE DATOS CON WORKBENCH
MANUAL DE DESPLIEGUE BASE DE DATOS CON WORKBENCH
 
CUESTIONARIO INTRODUCCION A UNITY 3D v2
CUESTIONARIO INTRODUCCION A UNITY 3D v2CUESTIONARIO INTRODUCCION A UNITY 3D v2
CUESTIONARIO INTRODUCCION A UNITY 3D v2
 
CUESTIONARIO INTRODUCCION A UNITY 3D
CUESTIONARIO INTRODUCCION A UNITY 3DCUESTIONARIO INTRODUCCION A UNITY 3D
CUESTIONARIO INTRODUCCION A UNITY 3D
 
MANUAL DESPLIEGUE SERVIDOR BASE DE DATOS
MANUAL DESPLIEGUE SERVIDOR BASE DE DATOSMANUAL DESPLIEGUE SERVIDOR BASE DE DATOS
MANUAL DESPLIEGUE SERVIDOR BASE DE DATOS
 
INTRODUCCION A SISTEMAS OPERATIVOS
INTRODUCCION A SISTEMAS OPERATIVOSINTRODUCCION A SISTEMAS OPERATIVOS
INTRODUCCION A SISTEMAS OPERATIVOS
 
CLASE 2 ORACLE CLOUD
CLASE 2 ORACLE CLOUDCLASE 2 ORACLE CLOUD
CLASE 2 ORACLE CLOUD
 
CASOS DE ESTUDIO MODELADO DEL NEGOCIO
CASOS DE ESTUDIO MODELADO DEL NEGOCIOCASOS DE ESTUDIO MODELADO DEL NEGOCIO
CASOS DE ESTUDIO MODELADO DEL NEGOCIO
 
MATERIAL DE ESTUDIO CCNA
MATERIAL DE ESTUDIO CCNAMATERIAL DE ESTUDIO CCNA
MATERIAL DE ESTUDIO CCNA
 
PREGUNTAS TOGAF 9.2 RESPUESTAS
PREGUNTAS TOGAF 9.2 RESPUESTASPREGUNTAS TOGAF 9.2 RESPUESTAS
PREGUNTAS TOGAF 9.2 RESPUESTAS
 

Recently uploaded

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 

Recently uploaded (20)

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 

PL/SQL CONDICIONALES Y CICLOS

  • 1.
  • 2. 2 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Database Programming with PL/SQL 4-1 Conditional Control: IF Statements
  • 3. 3 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Objectives •This lesson covers the following objectives: −Describe a use for conditional control structures −List the types of conditional control structures −Construct and use an IF statement −Construct and use an IF-THEN-ELSE statement −Create PL/SQL to handle the null condition in IF statements 3
  • 4. 4 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Purpose •In this section, you learn how to use the conditional logic in a PL/SQL block •Conditional processing extends the usefulness of programs by allowing the use of simple logical tests to determine which statements are executed 4
  • 5. 5 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Purpose •Think of a logic test as something you do every day •If you get up in the morning and it is cold outside, you will choose to wear cold-weather clothing •If you get up in the morning and it is warm outside, you will choose to wear warm-weather clothing •And if there is a chance of rain, then you will bring a rain coat or an umbrella with you 5
  • 6. The IF statement contains alternative courses of action in a block based on conditions. A condition is an expression with a TRUE or FALSE value that is used to make a decision. The CASE statement contains alternative courses of action in a block based on one condition. They are different in that they can be used outside of a PLSQL block in a SQL statement. LOOPs are control structures that allow iteration of statements. Loop control structures are repetition statements that enable you to execute statements in a PLSQL block repeatedly. There are three types of loop control structures supported by PL/SQL—BASIC, FOR, and WHILE. 6 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Controlling the Flow of Execution •You can change the logical flow of statements within the PL/SQL block with a number of control structures •This lesson introduces three types of PL/SQL control structures: −Conditional constructs with the IF statement −CASE expressions −LOOP control structures 6 FOR LOOP WHILE
  • 7. Writing in pseudocode combines natural language with code-like elements. It is sometimes used when introducing new structures and concepts. Pseudocode generally excludes syntax requirements and adds words that capture the logic of the structure/concept under consideration. 7 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statement •The IF statement shown below using "pseudocode" contains alternative courses of action in a block based on conditions •A condition is an expression with a TRUE or FALSE value that is used to make a decision 7 if the region_id is in (5, 13, 21) then print "AMERICAS" otherwise, if the region_id is in (11, 14, 15) then print "AFRICA" otherwise, if the region_id is in (30, 34, 35) then print "ASIA" Conditions
  • 8. CASE expressions will be discussed more fully in a future lesson. 8 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State CASE Expressions •CASE expressions are similar to IF statements in that they also determine a course of action based on conditions •They are different in that they can be used outside of a PLSQL block in an SQL statement •Consider the following pseudocode example: 8 if the region_id is 5 then print "AMERICAS" 13 then print "AMERICAS" 21 then print "AMERICAS" 11 then print "AFRICA" 14 then print "AFRICA" 15 then print "AFRICA" 30 then print "ASIA" …
  • 9. Loops will be discussed more fully in a future lesson. 9 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State LOOP Control Structures •Loop control structures are repetition statements that enable you to execute statements in a PLSQL block repeatedly •Three types of loop control structures are supported by PL/SQL: BASIC, FOR, and WHILE 9 FOR LOOP WHILE
  • 10. 10 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State LOOP Control Structures •Consider the following pseudocode example: −Print the numbers 1–5 by using a loop and a counter 10 Loop Counter equals: 1 Loop Counter equals: 2 Loop Counter equals: 3 Loop Counter equals: 4 Loop Counter equals: 5 Statement processed. FOR LOOP WHILE
  • 11. Please note the ELSIF does not have an 'E' after the 'S,' and there is no space. There can be many ELSIF clauses within an IF statement. There can be only one ELSE clause within an IF statement (and it comes just before the END IF). Also, each THEN clause within the IF statement ends with a semicolon. 11 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statements Structure •The structure of the PL/SQL IF statement is similar to the structure of IF statements in other procedural languages •It enables PL/SQL to perform actions selectively based on conditions •Syntax: 11 IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF;
  • 12. 12 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statements •Condition is a Boolean variable or expression that returns TRUE, FALSE, or NULL •THEN introduces a clause that associates the Boolean expression with the sequence of statements that follows it 12 IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF;
  • 13. 13 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statements •Statements can be one or more PL/SQL or SQL statements •They can include further IF statements containing several nested IF, ELSE, and ELSIF statements •The statements in the THEN clause are executed only if the condition in the associated IF clause evaluates to TRUE 13 IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF;
  • 14. 14 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statements •ELSIF is a keyword that introduces an additional Boolean expression •If the first condition yields FALSE or NULL, then the ELSIF keyword introduces additional conditions •ELSIF is the correct spelling, not ELSEIF 14 IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF;
  • 15. 15 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statements •ELSE introduces the default clause that is executed if, and only if, none of the earlier conditions (introduced by IF and ELSIF) are TRUE •The tests are executed in sequence so that a later condition that might be true is pre-empted by an earlier condition that is true •END IF; marks the end of an IF statement 15 IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF;
  • 16. 16 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statements Note •ELSIF and ELSE are optional in an IF statement •You can have any number of ELSIF keywords but only one ELSE keyword in your IF statement • END IF marks the end of an IF statement and must be terminated by a semicolon 16 IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF;
  • 17. 17 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Simple IF Statement •This is an example of a simple IF statement with a THEN clause •The v_myage variable is initialized to 31 17 DECLARE v_myage NUMBER := 31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child'); END IF; END;
  • 18. 18 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Simple IF Statement •The condition for the IF statement returns FALSE because v_myage is not less than 11 •Therefore, the control never reaches the THEN clause and nothing is printed to the screen 18 DECLARE v_myage NUMBER := 31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child'); END IF; END;
  • 19. 19 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF THEN ELSE Statement •The ELSE clause has been added to this example •The condition has not changed, thus it still evaluates to FALSE 19 DECLARE v_myage NUMBER:=31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child'); ELSE DBMS_OUTPUT.PUT_LINE('I am not a child'); END IF; END;
  • 20. 20 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF THEN ELSE Statement •Remember that the statements in the THEN clause are only executed if the condition returns TRUE •In this case, the condition returns FALSE, so control passes to the ELSE statement 20 DECLARE v_myage NUMBER:=31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child'); ELSE DBMS_OUTPUT.PUT_LINE('I am not a child'); END IF; END;
  • 21. 21 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF ELSIF ELSE Clause •The IF statement now contains multiple ELSIF clauses as well as an ELSE clause •Notice that the ELSIF clauses add additional conditions 21
  • 22. Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF ELSIF ELSE Clause 22 DECLARE v_myage NUMBER := 31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child'); ELSIF v_myage < 20 THEN DBMS_OUTPUT.PUT_LINE('I am young'); ELSIF v_myage < 30 THEN DBMS_OUTPUT.PUT_LINE('I am in my twenties'); ELSIF v_myage < 40 THEN DBMS_OUTPUT.PUT_LINE('I am in my thirties'); ELSE DBMS_OUTPUT.PUT_LINE('I am mature'); END IF; END; 22
  • 23. 23 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF ELSIF ELSE Clause •As with the IF statement, each ELSIF condition is followed by a THEN clause •This is executed only if the ELSIF condition returns TRUE 23
  • 24. Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF ELSIF ELSE Clause 24 DECLARE v_myage NUMBER := 31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child'); ELSIF v_myage < 20 THEN DBMS_OUTPUT.PUT_LINE('I am young'); ELSIF v_myage < 30 THEN DBMS_OUTPUT.PUT_LINE('I am in my twenties'); ELSIF v_myage < 40 THEN DBMS_OUTPUT.PUT_LINE('I am in my thirties'); ELSE DBMS_OUTPUT.PUT_LINE('I am mature'); END IF; END; 24
  • 25. The IF clause now contains multiple ELSIF clauses and an ELSE clause. Observe that the ELSIF clauses have conditions, but the ELSE clause has no condition. The condition for ELSIF should be followed by the THEN clause that is executed if the condition of the ELSIF clause returns TRUE. When you have multiple ELSIF clauses, if the first condition is FALSE or NULL, the control shifts to the next ELSIF clause. 25 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF ELSIF ELSE Clause •When you have multiple clauses in the IF statement and a condition is FALSE or NULL, control then passes to the next clause •Conditions are evaluated one by one •If all conditions are FALSE or NULL, then the statements in the ELSE clause are executed 25
  • 26. Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF ELSIF ELSE Clause 26 …IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF v_myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' I am young '); ELSIF v_myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' I am in my twenties '); ELSIF v_myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' I am in my thirties '); ELSE DBMS_OUTPUT.PUT_LINE(' I am always young '); END IF;… 26
  • 27. 27 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF ELSIF ELSE Clause •The final ELSE clause is optional 27 …IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF v_myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' I am young '); ELSIF v_myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' I am in my twenties '); ELSIF v_myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' I am in my thirties '); ELSE DBMS_OUTPUT.PUT_LINE(' I am always young '); END IF;…
  • 28. 28 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statement with Multiple Expressions •An IF statement can have multiple conditional expressions related with logical operators, such as AND, OR, and NOT • This example uses the AND operator •Therefore, it evaluates to TRUE only if both BOTH the first name and age conditions are evaluated as TRUE 28 DECLARE v_myage NUMBER := 31; v_myfirstname VARCHAR2(11) := 'Christopher'; BEGIN IF v_myfirstname ='Christopher' AND v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child named Christopher'); END IF; END;
  • 29. 29 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State IF Statement with Multiple Expressions •There is no limitation on the number of conditional expressions that can be used •However, these statements must be connected with the appropriate logical operators 29 DECLARE v_myage NUMBER := 31; v_myfirstname VARCHAR2(11) := 'Christopher'; BEGIN IF v_myfirstname ='Christopher' AND v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child named Christopher'); END IF; END;
  • 30. 30 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State NULL Values in IF Statements •In this example, the v_myage variable is declared but is not initialized •The condition in the IF statement returns NULL, which is neither TRUE nor FALSE •In such a case, the control goes to the ELSE statement because, just NULL is not TRUE 30
  • 31. Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State NULL Values in IF Statements 31 DECLARE v_myage NUMBER; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE('I am a child'); ELSE DBMS_OUTPUT.PUT_LINE('I am not a child'); END IF; END; 31
  • 32. 32 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Handling Nulls •When working with nulls, you can avoid some common mistakes by keeping in mind the following rules: −Simple comparisons involving nulls always yield NULL −Applying the logical operator NOT to a null yields NULL −In conditional control statements, if a condition yields NULL, it behaves just like a FALSE, and the associated sequence of statements is not executed 32
  • 33. 33 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Handling Nulls Example •In this example, you might expect the sequence of statements to execute because a and b seem equal •But, NULL is unknown, so we don't know if a and b are equal •The IF condition yields NULL and the THEN clause is bypassed, with control going to the line following the THEN clause 33 a := NULL; b := NULL; ... IF a = b THEN … -- yields NULL, not TRUE and the sequence of statements is not executed END IF;
  • 34. 34 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Guidelines for Using IF Statements •Follow these guidelines when using IF statements: −You can perform actions selectively when a specific condition is being met −When writing code, remember the spelling of the keywords: • ELSIF is one word • END IF is two words 34
  • 35. 35 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Guidelines for Using IF Statements •If the controlling Boolean condition is TRUE, then the associated sequence of statements is executed; if the controlling Boolean condition is FALSE or NULL, then the associated sequence of statements is passed over •Any number of ELSIF clauses is permitted •Indent the conditionally executed statements for clarity 35
  • 36. • CASE – An expression that determines a course of action based on conditions and can be used outside of a PL/SQL block in a SQL statement. • Condition – An expression with a TRUE or FALSE value that is used to make a decision. • IF – Statement that enables PL/SQL to perform actions selectively based on conditions. • LOOP– Control structures- Repetition statements that enable you to execute statements in a PL/SQL block repeatedly. 36 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Terminology •Key terms used in this lesson included: −CASE −Condition −IF −LOOP 36
  • 37. 37 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-1 Conditional Control: IF State Summary •In this lesson, you should have learned how to: −Describe a use for conditional control structures −List the types of conditional control structures −Construct and use an IF statement −Construct and use an IF-THEN-ELSE statement −Create PL/SQL to handle the null condition in IF statements 37
  • 38.
  • 39. 1
  • 40. 2 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Database Programming with PL/SQL 4-2 Conditional Control: Case Statements
  • 41. 3 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Objectives •This lesson covers the following objectives: −Construct and use CASE statements in PL/SQL −Construct and use CASE expressions in PL/SQL −Include the correct syntax to handle null conditions in PL/SQL CASE statements −Include the correct syntax to handle Boolean conditions in PL/SQL IF and CASE statements 3
  • 42. 4 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Purpose •In this lesson, you learn how to use CASE statements and CASE expressions in a PL/SQL block •CASE STATEMENTS are similar to IF statements, but are often easier to write and easier to read •CASE EXPRESSIONS work like functions to return one value from a number of values into a variable 4
  • 43. 5 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Using a CASE Statement •Look at this IF statement. What do you notice? •All the conditions test the same variable v_numvar •And the coding is very repetitive: v_numvar is coded many times 5 DECLARE v_numvar NUMBER; BEGIN ... IF v_numvar = 5 THEN statement_1; statement_2; ELSIF v_numvar = 10 THEN statement_3; ELSIF v_numvar = 12 THEN statement_4; statement_5; ELSIF v_numvar = 27 THEN statement_6; ELSIF v_numvar ... – and so on ELSE statement_15; END IF; ... END;
  • 44. The WHEN clauses, “WHEN 5,” “WHEN 10,” “WHEN 12,” etc. mean: WHEN v_numvar is equal to 5, and WHEN v_numvar is equal to 10, etc. 6 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Using a CASE Statement •Here is the same logic, but using a CASE statement •It is much easier to read. v_numvar is written only once 6 DECLARE v_numvar NUMBER; BEGIN ... CASE v_numvar WHEN 5 THEN statement_1; statement_2; WHEN 10 THEN statement_3; WHEN 12 THEN statement_4; statement_5; WHEN 27 THEN statement_6; WHEN ... – and so on ELSE statement_15; END CASE; ... END;
  • 45. 7 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements CASE Statements: An Example •A simple example to demonstrate the CASE logic 7 DECLARE v_num NUMBER := 15; v_txt VARCHAR2(50); BEGIN CASE v_num WHEN 20 THEN v_txt := 'number equals 20'; WHEN 17 THEN v_txt := 'number equals 17'; WHEN 15 THEN v_txt := 'number equals 15'; WHEN 13 THEN v_txt := 'number equals 13'; WHEN 10 THEN v_txt := 'number equals 10'; ELSE v_txt := 'some other number'; END CASE; DBMS_OUTPUT.PUT_LINE(v_txt); END;
  • 46. The same logic from above, rewritten using an IF statement: DECLARE v_num NUMBER := 15; v_txt VARCHAR2(50); BEGIN IF v_num > 20 THEN v_txt := 'greater than 20'; ELSIF v_num > 15 THEN v_txt := 'greater than 15'; ELSE v_txt := 'less than 16'; END IF; DBMS_OUTPUT.PUT_LINE(v_txt); END; 8 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Searched CASE Statements •You can use CASE statements to test for non-equality conditions such as <, >, >=, etc. •These are called searched CASE statements •The syntax is virtually identical to an equivalent IF statement 8 DECLARE v_num NUMBER := 15; v_txt VARCHAR2(50); BEGIN CASE WHEN v_num > 20 THEN v_txt := 'greater than 20'; WHEN v_num > 15 THEN v_txt := 'greater than 15'; ELSE v_txt := 'less than 16'; END CASE; DBMS_OUTPUT.PUT_LINE(v_txt); END;
  • 47. 9 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Using a CASE Expression •You want to assign a value to one variable that depends on the value in another variable •Look at this IF statement •Again, the coding is very repetitive 9 DECLARE v_out_var VARCHAR2(15); v_in_var NUMBER; BEGIN ... IF v_in_var = 1 THEN v_out_var := 'Low value'; ELSIF v_in_var = 50 THEN v_out_var := 'Middle value'; ELSIF v_in_var = 99 THEN v_out_var := 'High value'; ELSE v_out_var := 'Other value'; END IF; ... END;
  • 48. 10 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Using a CASE Expression •Here is the same logic, but using a CASE expression: 10 DECLARE v_out_var VARCHAR2(15); v_in_var NUMBER; BEGIN ... v_out_var := CASE v_in_var WHEN 1 THEN 'Low value' WHEN 50 THEN 'Middle value' WHEN 99 THEN 'High value' ELSE 'Other value' END; ... END;
  • 49. 11 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements CASE Expression Syntax •A CASE expression is different from a CASE statement because it selects one of a number of results and assigns it to a variable •A CASE expression ends with END not END CASE •In the syntax, expressionN can be a literal value or an expression such as (v_other_var * 2) 11 variable_name := CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1] END;
  • 50. Answer: Grade: C Appraisal: Good Statement processed. 12 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements CASE Expression Example •What would be the result of this code if v_grade was initialized as "C" instead of "A" 12 DECLARE v_grade CHAR(1) := 'A'; v_appraisal VARCHAR2(20); BEGIN v_appraisal := CASE v_grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE('Grade: ' || v_grade || ' Appraisal: ' || v_appraisal); END; RESULT: Grade: A Appraisal: Excellent Statement processed.
  • 51. Answer: "Same value" will be displayed. Remember, read the highlighted WHEN clause as, "When v_in_var is equal to v_in_var, then assign "Same value" to v_out_var and skip to the line following the CASE expression end." Since v_in_var is equal to itself, the code will display the phrase, "Same value." 13 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements CASE Expression: A Second Example •Determine what will be displayed when this block is executed: 13 DECLARE v_out_var VARCHAR2(15); v_in_var NUMBER := 20; BEGIN v_out_var := CASE v_in_var WHEN 1 THEN 'Low value' WHEN v_in_var THEN 'Same value' WHEN 20 THEN 'Middle value' ELSE 'Other value' END; DBMS_OUTPUT.PUT_LINE(v_out_var); END;
  • 52. Searched CASE expressions are more flexible, allowing non-equality conditions (and compound conditions) to be tested and different variables to be used in different WHEN clauses. 14 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Searched CASE Expression Syntax • PL/SQL also provides a searched CASE expression, which has the following form: • A searched CASE expression has no selector • Also, its WHEN clauses contain search conditions that yield a Boolean value, not expressions that can yield a value of any type 14 variable_name := CASE WHEN search_condition1 THEN result1 WHEN search_condition2 THEN result2 ... WHEN search_conditionN THEN resultN [ELSE resultN+1] END;
  • 53. We could have used a non-searched CASE expression. The example in the slide could be written as: v_appraisal := CASE v_ grade WHEN ‘A’ THEN ‘Excellent’ WHEN ‘B’ THEN ‘Good’ WHEN ‘C’ THEN ‘Good’ ELSE ‘No such grade’ END; 15 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Searched CASE Expressions: An Example •Searched CASE expressions allow non-equality conditions, compound conditions, and different variables to be used in different WHEN clauses 15 DECLARE v_grade CHAR(1) := 'A'; v_appraisal VARCHAR2(20); BEGIN v_appraisal := CASE -- no selector here WHEN v_grade = 'A' THEN 'Excellent' WHEN v_grade IN ('B','C') THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade || ' Appraisal ' || v_appraisal); END;
  • 54. CASE expressions are actually functions, which always return exactly one value. A common, built-in function is SYSDATE. Just like a CASE expression, SYSDATE assigns one value to a variable. v_date := SYSDATE; 16 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements How are CASE Expressions Different From CASE Statements? •They are different because: −CASE expressions return a value into a variable −CASE expressions end with END; −A CASE expression is a single PL/SQL statement 16 DECLARE v_grade CHAR(1) := 'A'; v_appraisal VARCHAR2(20); BEGIN v_appraisal := CASE WHEN v_grade = 'A' THEN 'Excellent' WHEN v_grade IN ('B','C') THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade || ' Appraisal ' || v_appraisal); END;
  • 55. A CASE expression has only one terminating semicolon at the END;, while a CASE statement has a semicolon after each executable statement in a WHEN clause. 17 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements How are CASE Expressions Different From CASE Statements? •CASE statements evaluate conditions and perform actions •A CASE statement can contain many PL/SQL statements •CASE statements end with END CASE; 17 DECLARE v_grade CHAR(1) := 'A'; BEGIN CASE WHEN v_grade = 'A' THEN DBMS_OUTPUT.PUT_LINE ('Excellent'); WHEN v_grade IN ('B','C') THEN DBMS_OUTPUT.PUT_LINE ('Good'); ELSE DBMS_OUTPUT.PUT_LINE('No such grade'); END CASE; END;
  • 56. You can build a simple Boolean condition by combining number, character, or date expressions with comparison operators. You can build a complex Boolean condition by combining simple Boolean conditions with the logical operators AND, OR, and NOT. The logical operators are used to check the Boolean variable values and return TRUE, FALSE, or NULL. Note: The negation of NULL (NOT NULL) results in a null value because null values are indeterminate. 18 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Logic Tables •When using IF and CASE statements you often need to combine conditions using AND, OR, and NOT •The following Logic Table displays the results of all possible combinations of two conditions •Example: TRUE and FALSE is FALSE 18 AND TRUE FALSE NULL OR TRUE FALSE NULL NOT TRUE TRUE Ex. FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL FALSE TRUE NULL NULL FALSE NULL NULL TRUE NULL NULL NULL NULL
  • 57. The AND Logic Table on the previous slide can help you evaluate the possibilities for the Boolean condition in this slide. Answers: 1. TRUE 2. FALSE 3. NULL 4. FALSE 19 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Boolean Conditions •What is the value of v_flag in each case? 19 v_flag := v_reorder_flag AND v_available_flag; V_REORDER_FLAG V_AVAILABLE_FLAG V_FLAG TRUE TRUE 1. _____ TRUE FALSE 2. _____ NULL TRUE 3. _____ NULL FALSE 4. _____
  • 58. • CASE expression – An expression that selects a result and returns it into a variable. • CASE statement – A block of code that performs actions based on conditional tests. • Logic Tables – Shows the results of all possible combinations of two conditions. 20 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Terminology •Key terms used in this lesson included: −CASE expression −CASE statement −Logic tables 20
  • 59. 21 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-2 Conditional Control: Case Statements Summary •In this lesson, you should have learned how to: −Construct and use CASE statements in PL/SQL −Construct and use CASE expressions in PL/SQL −Include the correct syntax to handle null conditions in PL/SQL CASE statements −Include the correct syntax to handle Boolean conditions in PL/SQL IF and CASE statements 21
  • 60. 22
  • 61. 1
  • 62. 2 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Database Programming with PL/SQL 4-3 Iterative Control: Basic Loops
  • 63. 3 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Objectives •This lesson covers the following objectives: −Describe the need for LOOP statements in PL/SQL −Recognize different types of LOOP statements −Create PL/SQL containing a basic loop and an EXIT statement −Create PL/SQL containing a basic loop and an EXIT statement with conditional termination 3
  • 64. 4 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Purpose •Looping constructs are the second type of control structure •Loops are mainly used to execute statements repeatedly until an EXIT condition is reached •PL/SQL provides three ways to structure loops to repeat a statement or a sequence of statements multiple times •These are basic loops, FOR loops, and WHILE loops •This lesson introduces the three loop types and discusses basic loops in greater detail 4 WARNING: When a user executes a PL/SQL block in APEX that contains an infinite loop, there is no way for the user to stop the loop. It can only be stopped by the DBA who oversees the Academy database. If the loop does not contain DML statements, closing the browser window and reopening it will allow the user to continue coding. If the block contains a FOR UPDATE clause, the affected table(s) will remain locked until released by the DBA, which may take a day or more. Be careful executing loops. All loops required by this course should have some type of limiting condition. NO infinite loops are required as part of this course.
  • 65. Each loop is structured for a specific purpose. These loops are used to write code to handle all situations (problems). Loops can repeat one statement, a group of statements, and/or a block. Loops have a scope and loop variables have a life. 5 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Iterative Control: LOOP Statements •Loops repeat a statement or a sequence of statements multiple times •PL/SQL provides the following types of loops: −Basic loops that perform repetitive actions without overall conditions −FOR loops that perform iterative actions based on a counter −WHILE loops that perform repetitive actions based on a condition 5
  • 66. 6 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Basic Loops •The simplest form of a LOOP statement is the basic loop, which encloses a sequence of statements between the keywords LOOP and END LOOP •Use the basic loop when the statements inside the loop must execute at least once 6
  • 67. 7 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Basic Loops Exit •Each time the flow of execution reaches the END LOOP statement, control is passed to the corresponding LOOP statement that introduced it •A basic loop allows the execution of its statements at least once, even if the EXIT condition is already met upon entering the loop •Without the EXIT statement, the loop would never end (an infinite loop) 7 BEGIN LOOP statements; EXIT [WHEN condition]; END LOOP; END;
  • 68. 8 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Basic Loops Simple Example •In this example, no data is processed •We simply display the loop counter each time we repeat the loop 8 DECLARE v_counter NUMBER(2) := 1; BEGIN LOOP DBMS_OUTPUT.PUT_LINE('Loop execution #' || v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 5; END LOOP; END;
  • 69. 9 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Basic Loops More Complex Example •In this example, three new location IDs for Montreal, Canada, are inserted in the LOCATIONS table 9 DECLARE v_loc_id locations.location_id%TYPE; v_counter NUMBER(2) := 1; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = 2; LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + v_counter), 'Montreal', 2); v_counter := v_counter + 1; EXIT WHEN v_counter > 3; END LOOP; END;
  • 70. 10 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Basic Loops EXIT Statement •You can use the EXIT statement to terminate a loop and pass control to the next statement after the END LOOP statement •You can issue EXIT as an action within an IF statement 10 DECLARE v_counter NUMBER := 1; BEGIN LOOP DBMS_OUTPUT.PUT_LINE('Counter is ' || v_counter); v_counter := v_counter + 1; IF v_counter > 10 THEN EXIT; END IF; END LOOP; END;
  • 71. 11 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Basic Loop EXIT Statement Rules •Rules: −The EXIT statement must be placed inside a loop −If the EXIT condition is placed at the top of the loop (before any of the other executable statements) and that condition is initially true, then the loop exits and the other statements in the loop never execute −A basic loop can contain multiple EXIT statements 11
  • 72. The statement, EXIT WHEN v_counter > 10, is logically identical to: IF v_counter > 10 THEN EXIT; END IF; However, in PL/SQL, the EXIT WHEN statement is the appropriate syntax. From a programmer's perspective, it is the more elegant solution. 12 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Basic Loop EXIT WHEN Statement •Although the IF…THEN EXIT works to end a loop, the correct way to end a basic loop is with the EXIT WHEN statement •If the WHEN clause evaluates to TRUE, the loop ends and control passes to the next statement following END LOOP 12 DECLARE v_counter NUMBER := 1; BEGIN LOOP DBMS_OUTPUT.PUT_LINE('Counter is ' || v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END;
  • 73. • Basic Loop – A sequence of statements between the keywords LOOP and END LOOP; the statements must execute at least once. • Counter – A counter is a variable that programmers use to keep track of the number of times a loop executes (or repeats). When a specific value is reached, it triggers the execution of the EXIT command which stops the loop from repeating, passing control to the first command following the END LOOP command. • END LOOP – A PL/SQL command that marks the end of the statements within a loop and returns control to the corresponding LOOP statement that introduced it (the loop begins again). • EXIT – Statement to terminate a loop. • LOOP – A PL/SQL command that marks the beginning of the statements within a loop. 13 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Terminology •Key terms used in this lesson included: −Basic Loop −Counter −END LOOP −EXIT −LOOP 13
  • 74. 14 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-3 Iterative Control: Basic Loops Summary •In this lesson, you should have learned how to: −Describe the need for LOOP statements in PL/SQL −Recognize different types of LOOP statements −Create PL/SQL containing a basic loop and an EXIT statement −Create PL/SQL containing a basic loop and an EXIT statement with conditional termination 14
  • 75. 15
  • 76. 1
  • 77. 2 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Database Programming with PL/SQL 4-4 Iterative Control: WHILE and FOR Loops
  • 78. 3 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops Objectives •This lesson covers the following objectives: −Construct and use the WHILE looping construct in PL/SQL −Construct and use the FOR looping construct in PL/SQL −Describe when a WHILE loop is used in PL/SQL −Describe when a FOR loop is used in PL/SQL 3
  • 79. 4 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops Purpose •The previous lesson discussed the basic loop, which allows the statements inside the loop to execute at least once •This lesson introduces the WHILE loop and FOR loop •The WHILE loop is a looping construct which requires the controlling condition be evaluated at the start of each iteration •The FOR loop should be used if the number of iterations is known 4
  • 80. Since the WHILE loop depends on a condition and is not fixed, use the WHILE loop when you don’t know in advance the number of times a loop must execute. 5 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops WHILE Loops •You can use the WHILE loop to repeat a sequence of statements until the controlling condition is no longer TRUE •The condition is evaluated at the start of each iteration •The loop terminates when the condition is FALSE or NULL •If the condition is FALSE or NULL at the initial execution of the loop, then no iterations are performed 5 WHILE condition LOOP statement1; statement2; . . . END LOOP;
  • 81. 6 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops WHILE Loops •In the syntax: •Condition is a Boolean variable or expression (TRUE, FALSE, or NULL) •Statement can be one or more PL/SQL or SQL statements 6 WHILE condition LOOP statement1; statement2; . . . END LOOP;
  • 82. 7 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops WHILE •In the syntax: •If the variables involved in the conditions do not change during the body of the loop, then the condition remains TRUE and the loop does not terminate •Note: If the condition yields NULL, then the loop is bypassed and control passes to the statement that follows the loop 7 WHILE condition LOOP statement1; statement2; . . . END LOOP;
  • 83. Notice the similarities and differences to the basic loop from the previous lesson: DECLARE v_loc_id locations.location_id%TYPE; v_counter NUMBER(2) := 1; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = 'CA'; LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + v_counter), 'Montreal', 'CA'); v_counter := v_counter + 1; EXIT WHEN v_counter > 3; END LOOP; 8 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops WHILE Loops •In this example, three new location IDs for Montreal, Canada, are inserted in the LOCATIONS table •The counter is explicitly declared in this example 8 DECLARE v_loc_id locations.location_id%TYPE; v_counter NUMBER := 1; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = 2; WHILE v_counter <= 3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + v_counter), 'Montreal', 2); v_counter := v_counter + 1; END LOOP; END;
  • 85. 9 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops WHILE Loops •With each iteration through the WHILE loop, a counter (v_counter) is incremented •If the number of iterations is less than or equal to the number 3, then the code within the loop is executed and a row is inserted into the locations table 9
  • 86. Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops WHILE Loops 10 DECLARE v_loc_id locations.location_id%TYPE; v_counter NUMBER := 1; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = 2; WHILE v_counter <= 3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + v_counter), 'Montreal', 2); v_counter := v_counter + 1; END LOOP; END; 10
  • 87. 11 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops WHILE Loops •After the counter exceeds the number of new locations for this city and country, the condition that controls the loop evaluates to FALSE and the loop is terminated 11 DECLARE v_loc_id locations.location_id%TYPE; v_counter NUMBER := 1; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = 2; WHILE v_counter <= 3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + v_counter), 'Montreal', 2); v_counter := v_counter + 1; END LOOP; END;
  • 88. 12 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops FOR Loops Described •FOR loops have the same general structure as the basic loop •In addition, they have a control statement before the LOOP keyword to set the number of iterations that PL/SQL performs 12 FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP;
  • 89. 13 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops FOR Loop Rules •FOR loop rules: −Use a FOR loop to shortcut the test for the number of iterations −Do not declare the counter; it is declared implicitly −lower_bound .. upper_bound is the required syntax 13 FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP;
  • 90. 14 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops FOR Loops Syntax •Counter is an implicitly declared integer whose value automatically increases or decreases (decreases if the REVERSE keyword is used) by 1 on each iteration of the loop until the upper or lower bound is reached •REVERSE causes the counter to decrement with each iteration from the upper bound to the lower bound • (Note that the lower bound is referenced first) 14 FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP;
  • 91. Note these examples for controlling the counter through the FOR loop: FOR i IN 1..5 LOOP …; -- successive values 1,2,3,4,5 FOR i IN REVERSE 1..5 LOOP …; -- successive values 5,4,3,2,1 FOR i IN REVERSE 5..1 LOOP …; -- will cause an error. 15 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops FOR Loops Syntax •lower_bound specifies the lower bound for the range of counter values •upper_bound specifies the upper bound for the range of counter values 15 FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP;
  • 92. 16 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops FOR Loop Example •You have already learned how to insert three new locations for the country code CA and the city Montreal by using the simple LOOP and the WHILE loop •The next slide shows you how to achieve the same by using the FOR loop 16
  • 93. Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops FOR Loop Example 17 DECLARE v_loc_id locations.location_id%TYPE; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = 2; FOR i IN 1..3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + i), 'Montreal', 2); END LOOP; END; 17
  • 94. 18 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops FOR Loop Guidelines •FOR loops are a common structure of programming languages •A FOR loop is used within the code when the beginning and ending value of the loop is known •Reference the counter only within the loop; its scope does not extend outside the loop •Do not reference the counter as the target of an assignment •Neither loop bound (lower or upper) should be NULL 18
  • 95. 19 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops FOR Loop Expression Example •While writing a FOR loop, the lower and upper bounds of a LOOP statement do not need to be numeric literals •They can be expressions that convert to numeric values 19 DECLARE v_lower NUMBER := 1; v_upper NUMBER := 100; BEGIN FOR i IN v_lower..v_upper LOOP ... END LOOP; END;
  • 96. Note: All loops allow the use of an EXIT WHEN condition allowing the loop to terminate before the WHILE condition is false or the upper bound of the FOR loop is reached Remember that all the variables used within the loop block have a scope. The specific loop needed is determined by the problem being solved. 20 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops Guidelines For When to Use Loops •Use the basic loop when the statements inside the loop must execute at least once •Use the WHILE loop if the condition has to be evaluated at the start of each iteration •Use a FOR loop if the number of iterations is known 20
  • 97. • FOR Loop – Repeats a sequence of statements until a set number of iterations are fulfilled. • Lower Bound – The FOR loop syntax that specifies the lower bound for the range of counter values. • REVERSE – A PL/SQL command that causes the FOR loop counter to decrement with each iteration from the upper bound to the lower bound. • Upper Bound – The FOR loop syntax that specifies the upper bound for the range of counter values. • WHILE Loop – Repeats a sequence of statements until the controlling condition is no longer TRUE. 21 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops Terminology •Key terms used in this lesson included: −FOR loops −Lower Bound −REVERSE −Upper Bound −WHILE loops 21
  • 98. 22 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-4 Iterative Control: WHILE and FOR Loops Summary •In this lesson, you should have learned how to: −Construct and use the WHILE looping construct in PL/SQL −Construct and use the FOR looping construct in PL/SQL −Describe when a WHILE loop is used in PL/SQL −Describe when a FOR loop is used in PL/SQL 22
  • 99. 23
  • 100. 1
  • 101. 2 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Database Programming with PL/SQL 4-5 Iterative Control: Nested Loops
  • 102. 3 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Objectives •This lesson covers the following objectives: −Construct and execute PL/SQL using nested loops −Label loops and use the labels in EXIT statements −Evaluate a nested loop construct and identify the exit point 3
  • 103. 4 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Purpose •You’ve learned about looping constructs in PL/SQL •This lesson discusses how you can nest loops to multiple levels •You can nest FOR, WHILE, and basic loops within one another 4
  • 104. The slide example shows a FOR loop nested inside another FOR loop. But (for example) we could nest a WHILE loop inside a FOR loop; or a FOR loop inside a basic loop; or etc. All combinations are allowed. 5 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Nested Loop Example •In PL/SQL, you can nest loops to multiple levels •You can nest FOR, WHILE, and basic loops within one another 5 BEGIN FOR v_outerloop IN 1..3 LOOP FOR v_innerloop IN REVERSE 1..5 LOOP DBMS_OUTPUT.PUT_LINE('Outer loop is: ' || v_outerloop || ' and inner loop is: ' || v_innerloop); END LOOP; END LOOP; END;
  • 105. Answer : We will discuss loop labels in the next slides to answer this question. Notice that when V_INNER_DONE = 'YES', PL/SQL exits the inner loop but the outer loop continues executing. 6 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Nested Loops •This example contains EXIT conditions in nested basic loops •What if you want to exit from the outer loop at step A? 6 DECLARE v_outer_done CHAR(3) := 'NO'; v_inner_done CHAR(3) := 'NO'; BEGIN LOOP -- outer loop ... LOOP -- inner loop ... ... -- step A EXIT WHEN v_inner_done = 'YES'; ... END LOOP; ... EXIT WHEN v_outer_done = 'YES'; ... END LOOP; END;
  • 106. 7 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Loop Labels •Loop labels are required in this example in order to exit an outer loop from within an inner loop 7 DECLARE ... BEGIN <<outer_loop>> LOOP -- outer loop ... <<inner_loop>> LOOP -- inner loop EXIT outer_loop WHEN ... -- exits both loops EXIT WHEN v_inner_done = 'YES'; ... END LOOP; ... EXIT WHEN v_outer_done = 'YES'; ... END LOOP; END;
  • 107. 8 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Loop Labels •Loop label names follow the same rules as other identifiers •A label is placed before a statement, either on the same line or on a separate line •In FOR or WHILE loops, place the label before FOR or WHILE within label delimiters (<<label>>) •If the loop is labeled, the label name can optionally be included after the END LOOP statement for clarity 8
  • 108. The loop labels are not required in this example, but they do make the code more readable. 9 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Loop Labels •Label basic loops by placing the label before the word LOOP within label delimiters (<<label>>) 9 DECLARE v_outerloop PLS_INTEGER := 0; v_innerloop PLS_INTEGER := 5; BEGIN <<outer_loop>> LOOP v_outerloop := v_outerloop + 1; v_innerloop := 5; EXIT WHEN v_outerloop > 3; <<inner_loop>> LOOP DBMS_OUTPUT.PUT_LINE('Outer loop is: ' || v_outerloop || ' and inner loop is: ' || v_innerloop); v_innerloop := v_innerloop - 1; EXIT WHEN v_innerloop = 0; END LOOP inner_loop; END LOOP outer_loop; END;
  • 109. 10 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Nested Loops and Labels •In this example, there are two loops •The outer loop is identified by the label <<outer_loop>>, and the inner loop is identified by the label <<inner_loop>> •We reference the outer loop in the EXIT statement from within the inner_loop 10
  • 110. Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Nested Loops and Labels 11 ...BEGIN <<outer_loop>> LOOP v_counter := v_counter + 1; EXIT WHEN v_counter > 10; <<inner_loop>> LOOP ... EXIT outer_loop WHEN v_total_done = 'YES'; -- Leave both loops EXIT WHEN v_inner_done = 'YES'; -- Leave inner loop only ... END LOOP inner_loop; ... END LOOP outer_loop; END; 11
  • 111. • Label Delimiters – Characters placed before (<<) and after (>>) a loop label to identify the label as a loop label. • Loop Label – A loop identifier that is required in order to exit an outer loop from within an inner loop. 12 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Terminology •Key terms used in this lesson included: −Label Delimiters −Loop Label 12
  • 112. 13 Copyright © 2020, Oracle and/or its affiliates. All rights reserved. PLSQL 4-5 Iterative Control: Nested Loops Summary •In this lesson, you should have learned how to: −Construct and execute PL/SQL using nested loops −Label loops and use the labels in EXIT statements −Evaluate a nested loop construct and identify the exit point 13
  • 113. 14