Monday, August 29, 2016

PL/SQL - Loops

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:
Loop Architecture
PL/SQL provides the following types of loop to handle the looping requirements. Click the following links to check their detail.
Loop TypeDescription
In this loop structure, sequence of statements is enclosed between the LOOP and END LOOP statements. At each iteration, the sequence of statements is executed and then control resumes at the top of the loop.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
You can use one or more loop inside any another basic loop, while or for loop.

PL/SQL - WHILE LOOP Statement


WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given condition is true.

Syntax:

WHILE condition LOOP
   sequence_of_statements
END LOOP;

Example:

DECLARE
   a number(2) := 10;
BEGIN
   WHILE a < 20 LOOP
      dbms_output.put_line('value of a: ' || a);
      a := a + 1;
   END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

Labeling a PL/SQL Loop

PL/SQL loops can be labeled. The label should be enclosed by double angle brackets (<< and >>) and appear at the beginning of the LOOP statement. The label name can also appear at the end of the LOOP statement. You may use the label in the EXIT statement to exit from the loop.
The following program illustrates the concept:
DECLARE
   i number(1);
   j number(1);
BEGIN
   << outer_loop >>
   FOR i IN 1..3 LOOP
      << inner_loop >>
      FOR j IN 1..3 LOOP
         dbms_output.put_line('i is: '|| i || ' and j is: ' || j);
      END loop inner_loop;
   END loop outer_loop;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
i is: 1 and j is: 1
i is: 1 and j is: 2
i is: 1 and j is: 3
i is: 2 and j is: 1
i is: 2 and j is: 2
i is: 2 and j is: 3
i is: 3 and j is: 1
i is: 3 and j is: 2
i is: 3 and j is: 3

PL/SQL procedure successfully completed. 

PL/SQL - FOR LOOP Statement

FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

FOR counter IN initial_value .. final_value LOOP
   sequence_of_statements;
END LOOP;
Here is the flow of control in a for loop:
  • The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables.
  • Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the body of the loop is executed. If it is FALSE, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
  • After the body of the for loop executes, the value of the countervariable is increased or decreased.
  • The condition is now evaluated again. If it is TRUE, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes FALSE, the FOR-LOOP terminates.
Following are some special characteristics of PL/SQL for loop:
  • The initial_value and final_value of the loop variable or counter can be literals, variables, or expressions but must evaluate to numbers. Otherwise, PL/SQL raises the predefined exception VALUE_ERROR.
  • The initial_value need not to be 1; however, the loop counter increment (or decrement) must be 1.
  • PL/SQL allows determine the loop range dynamically at run time.

Example:

DECLARE
   a number(2);
BEGIN
   FOR a in 10 .. 20 LOOP
       dbms_output.put_line('value of a: ' || a);
  END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

PL/SQL procedure successfully completed.

Reverse FOR LOOP Statement

By default, iteration proceeds from the initial value to the final value, generally upward from the lower bound to the higher bound. You can reverse this order by using the REVERSE keyword. In such case, iteration proceeds the other way. After each iteration, the loop counter is decremented.
However, you must write the range bounds in ascending (not descending) order. The following program illustrates this:
DECLARE
   a number(2) ;
BEGIN
   FOR a IN REVERSE 10 .. 20 LOOP
      dbms_output.put_line('value of a: ' || a);
   END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11
value of a: 10

PL/SQL procedure successfully completed.

PL/SQL - Nested Loops

PL/SQL allows using one loop inside another loop. Following section shows few examples to illustrate the concept.
The syntax for a nested basic LOOP statement in PL/SQL is as follows:
LOOP
   Sequence of statements1
   LOOP
      Sequence of statements2
   END LOOP;
END LOOP;
The syntax for a nested FOR LOOP statement in PL/SQL is as follows:
FOR counter1 IN initial_value1 .. final_value1 LOOP
   sequence_of_statements1
   FOR counter2 IN initial_value2 .. final_value2 LOOP
      sequence_of_statements2
   END LOOP;
END LOOP;
The syntax for a nested WHILE LOOP statement in Pascal is as follows:
WHILE condition1 LOOP
   sequence_of_statements1
   WHILE condition2 LOOP
      sequence_of_statements2
   END LOOP;
END LOOP;

Example:

The following program uses a nested basic loop to find the prime numbers from 2 to 100:
DECLARE
   i number(3);
   j number(3);
BEGIN
   i := 2;
   LOOP
      j:= 2;
      LOOP
         exit WHEN ((mod(i, j) = 0) or (j = i));
         j := j +1;
      END LOOP;
   IF (j = i ) THEN
      dbms_output.put_line(i || ' is prime');
   END IF;
   i := i + 1;
   exit WHEN i = 50;
   END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

PL/SQL procedure successfully completed. 

The Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
PL/SQL supports the following control statements. Labeling loops also helps in taking the control outside a loop. Click the following links to check their details.
Control StatementDescription
The Exit statement completes the loop and control passes to the statement immediately after END LOOP
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Transfers control to the labeled statement. Though it is not advised to use GOTO statement in you

PL/SQL - EXIT Statement


The EXIT statement in PL/SQL programming language has following two usages:
  • When the EXIT statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
  • If you are using nested loops (i.e. one loop inside another loop), the EXIT statement will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:

The syntax for an EXIT statement in PL/SQL is as follows:
EXIT;

Flow Diagram:

PL/SQL exit statement

Example:

DECLARE
   a number(2) := 10;
BEGIN
   -- while loop execution 
   WHILE a < 20 LOOP
      dbms_output.put_line ('value of a: ' || a);
      a := a + 1;
      IF a > 15 THEN
         -- terminate the loop using the exit statement
         EXIT;
      END IF;
   END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

PL/SQL procedure successfully completed. 

The EXIT WHEN Statement

The EXIT-WHEN statement allows the condition in the WHEN clause to be evaluated. If the condition is true, the loop completes and control passes to the statement immediately after END LOOP.
Following are two important aspects for the EXIT WHEN statement:
  • Until the condition is true, the EXIT-WHEN statement acts like a NULL statement, except for evaluating the condition, and does not terminate the loop.
  • A statement inside the loop must change the value of the condition.

Syntax:

The syntax for an EXIT WHEN statement in PL/SQL is as follows:
EXIT WHEN condition;
The EXIT WHEN statement replaces a conditional statement like if-thenused with the EXIT statement.

Example:

DECLARE
   a number(2) := 10;
BEGIN
   -- while loop execution 
   WHILE a < 20 LOOP
      dbms_output.put_line ('value of a: ' || a);
      a := a + 1;
      -- terminate the loop using the exit when statement
   EXIT WHEN a > 15;
   END LOOP;
END;  
/
When the above code is executed at SQL prompt, it produces the following result:

value of a
: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15


PL/SQL procedure successfully completed.

PL/SQL - CONTINUE Statement


The CONTINUE statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. In other words, it forces the next iteration of the loop to take place, skipping any code in between.

Syntax:

The syntax for a CONTINUE statement is as follows:
CONTINUE;

Flow Diagram:

PL/SQL continue statement

Example:

DECLARE
   a number(2) := 10;
BEGIN
   -- while loop execution 
   WHILE a < 20 LOOP
      dbms_output.put_line ('value of a: ' || a);
      a := a + 1;
      IF a = 15 THEN
         -- skip the loop using the CONTINUE statement
         a := a + 1;
         CONTINUE;
      END IF;
   END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
 
PL/SQL procedure successfully completed. 

PL/SQL - GOTO Statement

A GOTO statement in PL/SQL programming language provides an unconditional jump from the GOTO to a labeled statement in the same subprogram.
NOTE: Use of GOTO statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a GOTO can be rewritten so that it doesn't need the GOTO.

Syntax:

The syntax for a GOTO statement in PL/SQL is as follows:
GOTO label;
..
..
<< label >>
statement;

Flow Diagram:

PL/SQL goto statement

Example:

DECLARE
   a number(2) := 10;
BEGIN
   <<loopstart>>
   -- while loop execution 
   WHILE a < 20 LOOP
      dbms_output.put_line ('value of a: ' || a);
      a := a + 1;
      IF a = 15 THEN
         a := a + 1;
         GOTO loopstart;
      END IF;
   END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed. 

Restrictions with GOTO Statement

GOTO Statement in PL/SQL imposes the following restrictions:
  • A GOTO statement cannot branch into an IF statement, CASE statement, LOOP statement or sub-block.
  • A GOTO statement cannot branch from one IF statement clause to another or from one CASE statement WHEN clause to another.
  • A GOTO statement cannot branch from an outer block into a sub-block (that is, an inner BEGIN-END block).
  • A GOTO statement cannot branch out of a subprogram. To end a subprogram early, either use the RETURN statement or have GOTO branch to a place right before the end of the subprogram.
  • A GOTO statement cannot branch from an exception handler back into the current BEGIN-END block. However, a GOTO statement can branch from an exception handler into an enclosing block.

No comments:

Post a Comment

Oracle Fusion - Cost Lines and Expenditure Item link in Projects

SELECT   ccd.transaction_id,ex.expenditure_item_id,cacat.serial_number FROM fusion.CST_INV_TRANSACTIONS cit,   fusion.cst_cost_distribution_...