Answer: Recall the script ch08_4a.sql:
SET SERVEROUTPUT ON DECLARE v_factorial NUMBER := 1; BEGIN FOR v_counter IN 1..10 LOOP v_factorial := v_factorial * v_counter; END LOOP; -- control resumes here DBMS_OUTPUT.PUT_LINE ('Factorial of ten is: '|| v_factorial); END;
Next, consider a new version of the script that uses a simple loop. All changes are shown in bold letters.
SET SERVEROUTPUT ON DECLARE v_counter NUMBER := 1; v_factorial NUMBER := 1; BEGIN LOOP v_factorial := v_factorial * v_counter; v_counter := v_counter + 1; EXIT WHEN v_counter = 10; END LOOP; -- control resumes here DBMS_OUTPUT.PUT_LINE ('Factorial of ten is: '|| v_factorial); END;
In this version of the script, you replace a numeric FOR loop with a simple loop. As a result, there are three important changes that you should make. First, you need to declare and initialize the loop counter, v_counter. This counter is implicitly defined and initialized by the FOR loop. Second, you need to increment the value of the loop counter. This is very important because if you forget to include the statement
v_counter := v_counter + 1;
in the body of the simple loop, you will end up with an infinite loop. The step is not necessary when using numeric FOR loop because it is done by the loop itself.
Third, you need to specify the EXIT condition for the simple loop. Because you are computing a factorial of 10, the following EXIT condition is specified:
EXIT WHEN v_counter = 10;
Notice that you could specify this EXIT condition using IF-THEN statement as well:
IF v_counter = 10 THEN EXIT; END IF;
When run, this example shows the following output:
Factorial of ten is: 362880 PL/SQL procedure successfully completed.