The simplicity and easy to use behavior of FOR loop has won the hearts of millions and has become the most widely used loop in programming. In PL/SQL we have two types of FOR loops:
FOR loop allows you to execute the block of statements repeatedly for a fixed number of time whereas WHILE loop is better suited when the number of iterations are unknown. [Click Here To Tweet This]
This tutorial will concentrate on Numeric “FOR LOOP”. We’ll leave the Cursor FOR loop for the future when we will learn the concepts of Cursor.
Here we only have the execution section and inside that we have our FOR loop which will print the value of v_counter variable from 1 to 10.
Have you noticed that we didn’t declare the v_counter variable anywhere in the program? Even we don’t have the declaration section here in this code. This is because variable v_counter is an implicit index integer variable which gets declared automatically with the definition of FOR loop. Moreover the variable v_counter will increment by 1 with each iteration automatically by FOR loop construct thus you do not need to write update statement (v_counter := v_counter +1) explicitly. As a matter of fact if you will try to write the update statement in the “FOR loop” then you will get an error.
In this example we need one extra variable to store the result of the multiplication thus we declared a variable v_result with NUMBER data type. In the execution section we have our “FOR loop” and this time inside the loop we have only two statements. First is an arithmetic expression which will perform the multiplication of our table and will store the result in v_result variable. Second is the output statement which will display you the result in a formatted manner.
That is all about Numeric FOR loop in PL/SQL. Hope you enjoyed reading and learnt something. Please do share this tutorial on your social media and with your friends. Also you can send me your feedback on my twitter @RebellionRider. Thanks & have a great day!
You can DOWNLOAD SQL script and presentation used in the Video and in this article.