0% found this document useful (0 votes)
17 views

Loop in PLSQL Explanation

Uploaded by

bunnybearcoder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Loop in PLSQL Explanation

Uploaded by

bunnybearcoder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

• Good afternoon everyone, let’s discuss Loops in PL/SQL.

• As a quick overview, PL/SQL is the procedural extension for sql, and being
a block language it combines SQL with the procedural features such as
control statements, loops, functions, etc.
• Now, What are loops? Just as the name suggests a loop statement
provides a way of repeating a particular part of any program or any code
block as many times as required.
• This image on the right describes the general working of a loop statement
in most of the programming languages.
• Explaining the ow diagram in the image: As we can see here if compiler
encounters a condition, it checks if the condition is true, it execute the
conditional code, if the condition fails, it exits the control statement,
• This is almost same as the working of the control statements, but. There
may be situations when we need to execute a block of code several times
or need to nd the occurrence of a particular result, we use loop in such
scenarios.
===============================================
• PL/SQL provides the following types of loops for handling the looping
requirements.
• Basic loop
• FOR loop
• While loop
• Nested loop
================================================
Now lets explore each loop in detail.
First is the Basic loop
• BASIC LOOP: Basic loop or simple loop is preferred in PL/SQL code when
there is no surety about how many times the block of code is to be
repeated.
• When we use the basic loop the code block will be executed at least once.
• While using it, following two things must be considered:
• Simple loop always begins with the keyword LOOP and ends with a
keyword END LOOP.
• A basic/simple loop can be terminated at any given point by using the exit
statement or by specifying certain condition by using the statement exit
when.
• Image1: This PL/SQL code initializes a variable `x` with a value of 10 and
enters a loop. Within the loop, it prints the current value of `x` using
`dbms_output.put_line` and increments `x` by 10. It checks if `x` exceeds 50,
and if so, exits the loop. After exiting the loop, it prints the nal value of `x`
concatenated with a message. In essence, it prints multiples of 10 until
reaching or exceeding 50, then displays the nal value of `x`.
When the above code is executed at the SQL prompt, it produces the
following result −
fi
fl
fi
fi
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.

• Image2: This PL/SQL code initialises a variable `x` with a value of 10 and
enters a loop. Within the loop, it prints the current value of `x` using
`dbms_output.put_line` and increments `x` by 10. It exits the loop when `x`
exceeds 50 using the `EXIT WHEN` statement. After exiting the loop, it
prints the nal value of `x` concatenated with a message. Essentially, it
prints multiples of 10 until reaching or exceeding 50, then displays the nal
value of `x`. Using `EXIT WHEN` streamlines the code by combining the exit
condition with the loop structure.
When the above code is executed at the SQL prompt, it produces the
following result −

10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.

PL/SQL Continue Statement


The continue statement is used to exit the loop from the reminder if
its body either conditionally or unconditionally and forces the next
iteration of the loop to take place, skipping any codes in between.

The continue statement is not a keyword in Oracle 10g. It is a new


feature incorporated in oracle 11g.

For example: If a continue statement exits a cursor FOR LOOP


prematurely then it exits an inner loop and transfer control to the
next iteration of an outer loop, the cursor closes (in this context,
CONTINUE works like GOTO).
fi
fi
Let's take an example of PL/SQL continue statement.

1. DECLARE
2. x NUMBER := 0;
3. BEGIN
4. LOOP -- After CONTINUE statement, control resumes here
5. DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' ||
TO_CHAR(x));
6. x := x + 1;
7. IF x < 3 THEN
8. CONTINUE;
9. END IF;
10. DBMS_OUTPUT.PUT_LINE
11. ('Inside loop, after CONTINUE: x = ' || TO_CHAR(x));
12. EXIT WHEN x = 5;
13. END LOOP;
14.
15. DBMS_OUTPUT.PUT_LINE (' After loop: x = ' ||
TO_CHAR(x));
16. END;
17. /
After the execution of above code, you will get the following result:

Inside loop: x = 0
Inside loop: x = 1
Inside loop: x = 2
Inside loop, after CONTINUE: x = 3
Inside loop: x = 3
Inside loop, after CONTINUE: x = 4
Inside loop: x = 4
Inside loop, after CONTINUE: x = 5
After loop: x = 5
=================================================
• PL/SQL: For Loop
• This loop is used when some statements in PL/SQL code block are to be
repeated for a xed number of times.
fi
• When we use the for loop we are supposed to de ne a counter variable
which decides how many time the loop will be executed based on a
starting and ending value provided at the beginning of the loop.
• The for loop automatically increments the value of the counter variable by 1
at the end of each loop cycle.
• The programmer need not have to write any instruction for incrementing or
decrementing value.
• These are some special characteristics of loop in PL/SQL.

• Following is the ow of control in a For Loop −
• The initial step is executed rst, and only once. This step allows you to
declare and initialise any loop control variables.
• Next, the condition, i.e., initial_value .. nal_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 the ow of control jumps to the next statement just after
the for loop.
• After the body of the for loop executes, the value of the counter variable 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.

Image1: This PL/SQL code declares a variable `a` of type number with a
precision of 2. It then enters a `FOR` loop where `a` iterates over the range
from 10 to 20 inclusively. Within the loop, it prints the current value of `a`
concatenated with a message using `dbms_output.put_line`. The loop
iterates from 10 to 20, printing each value of `a`. Finally, the program
completes execution.

Image2: This PL/SQL code declares a variable `a` of type number with a
precision of 2. It then enters a `FOR` loop where `a` iterates over the range
from 20 to 10 inclusively in reverse order, as speci ed by the `REVERSE`
keyword. Within the loop, it prints the current value of `a` concatenated with
a message using `dbms_output.put_line`. The loop iterates from 20 down to
10, printing each value of `a` in reverse order. Finally, the program completes
execution.
========================================
WHILE LOOP
It is an entry controlled loop which means that before entering in a while loop
rst the condition is tested, if the condition is TRUE the statement or a group
of statements get executed and if the condition is FALSE the control will
move out of the while loop.

IMP sets to follow while using WHILE LOOP is:


fi
fl
fl
fi
fi
fi
fi
• Initialize a variable before the loop body.
• Increment the variable in the loop.
• You can use EXIT WHEN statements and EXIT statements in While loop but
it is not done often.

Image1: This PL/SQL code declares a variable `a` of type number with a
precision of 2 and initializes it to 10. It then enters a `WHILE` loop with the
condition `a < 20`. Within the loop, it prints the current value of `a`
concatenated with a message using `dbms_output.put_line`, and increments
`a` by 1 in each iteration. The loop continues executing as long as the
condition `a < 20` remains true. Once `a` reaches 20 or exceeds it, the loop
terminates, and the program completes execution. Essentially, it prints the
values of `a` from 10 up to (but not including) 20.
========================================
Nested Loop is a Loop inside Loop and PL/SQL supports nested loops that
allows you to have multiple levels of iteration within a program. This is
achieved by placing one or more LOOP statements inside another. Each
nested loop has its own set of loop control statements.

Image1: This PL/SQL code generates prime numbers up to 50. It initializes


two variables i and j to 2. It then enters a nested loop where i represents
each number to be checked for primality, and j iterates from 2 up to i.
Within the inner loop, it checks if i is divisible by j using the mod function. If i
is divisible by any number other than 1 or itself, the loop exits, indicating i is
not prime. If j reaches i without nding a divisor other than 1, it means i is
prime, and it prints that information using dbms_output.put_line.
After each iteration, i is incremented by 1. The outer loop continues until i
reaches 50.
========================================

When it comes to coding rules and standards for loops in PL/SQL, it's
essential to ensure readability, maintainability, and performance of your
code. Here are some commonly accepted guidelines:

1. **Use Meaningful Loop Names**: Give descriptive names to your loops


that indicate their purpose or what they iterate over. This enhances
readability and understanding.

2. **Avoid In nite Loops**: Always include an exit condition to prevent


in nite loops. Make sure your loop will eventually terminate under all
circumstances.

3. **Use FOR Loops When Possible**: If you know the number of iterations
beforehand, use `FOR` loops. They are more concise and easier to read.
fi
fi
fi
```plsql
FOR i IN 1..10 LOOP
-- Loop body
END LOOP;
```

4. **Avoid Nested Loops**: Excessive nesting of loops can make code hard
to understand and maintain. If possible, refactor nested loops into separate
functions or simplify the logic.

5. **Minimize Loop Body**: Keep the logic within the loop body as concise
as possible. If the loop body becomes too complex, consider refactoring it
into a separate function or procedure.

6. **Prefer Cursor FOR Loops for Record Processing**: When iterating


over query results, use `FOR` loops with cursor variables (`CURSOR FOR`)
instead of explicit cursors. This simpli es code and improves performance.

```plsql
FOR rec IN (SELECT * FROM your_table) LOOP
-- Access elds using rec. eld_name
END LOOP;
```

7. **Use EXIT and CONTINUE Sparingly**: While `EXIT` and `CONTINUE`


statements can be useful, excessive use can make code harder to follow.
Use them judiciously and consider if there are clearer alternatives.

8. **Optimize Performance**: Avoid unnecessary operations within loops,


especially database calls. If possible, move expensive operations outside the
loop or batch process data.

9. **Document Complex Loops**: If a loop contains complex logic or is


performance-critical, document it thoroughly to explain its purpose,
expected behavior, and any optimization techniques used.

10. **Follow Team Standards**: If you're working in a team, adhere to the


agreed-upon coding standards and guidelines. Consistency across the
codebase is crucial for collaboration and maintenance.

By following these guidelines, you can write cleaner, more e cient PL/SQL
code with loops that are easier to understand and maintain.
fi
fi
fi
ffi

You might also like