0

This is my PL/SQL WHILE LOOP code below:

SET SERVEROUTPUT ON;

DECLARE
l_check NUMBER;
BEGIN
WHILE (l_check < 5)
LOOP
l_check := l_check + 1;
DBMS_OUTPUT.PUT_LINE(l_check);
END LOOP;
END;

When I executed this while loop, it is showing in the message that PL/SQL procedure successfully completed. However, I'm getting a blank result despite using SET SERVEROUTPUT ON;

1 Answer 1

1

You haven't initialised l_check so it is NULL the first time it is tested in the WHILE loop. NULL is not less than 5 so the code never enters the loop.

Try to initialize the variable before loop:

SET SERVEROUTPUT ON;

DECLARE
    l_check NUMBER := 0;
BEGIN
    WHILE (l_check < 5)
    LOOP
        l_check := l_check + 1;
        DBMS_OUTPUT.PUT_LINE(l_check);
    END LOOP;
END;
Sign up to request clarification or add additional context in comments.

3 Comments

DECLARE l_check NUMBER := 1; BEGIN WHILE (l_check < 5) LOOP DBMS_OUTPUT.PUT_LINE(l_check); l_check := l_check + 1; END LOOP; END; It worked when I have put DBMS_OUTPUT statement before l_check := l_check + 1;
@stranger - the important change is ` l_check NUMBER := 1;`. Assigning a value to the variable means it's not null when you test the WHILE condition
The initial value (0 or 1 or anything else), where you do that (in the DECLARE section or in the execution section), and when you print the current value of l_check (before or after incrementing it) will have little effect, other than on exactly which values are printed. They all work the same way. If you want values from 1 to 4, or from 1 to 5, etc., you can adjust the initial value, the placement of the PUT_LINE command, and/or the exit condition (l_check < 5 vs. <= 5 etc.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.