LOOP
Example
Section titled “Example”DECLARE i NUMBER;BEGIN FOR i IN 1..5 LOOP DBMS_OUTPUT.PUT_LINE(i); END LOOP;END;/Output
Section titled “Output”12345Explanation
Section titled “Explanation”The provided code is an example of a basic loop in SQL that prints the numbers 1 through 5. The loop begins with the keyword FOR followed by the variable i in the range of 1 to 5 using the IN keyword. The loop processes each number in this range. Inside the loop, DBMS_OUTPUT.PUT_LINE(i) is used to print the current value of i. The loop ends with the END LOOP statement.
Example
Section titled “Example”DECLARE @counter INT;SET @counter = 1;
WHILE @counter <= 5BEGIN PRINT @counter; SET @counter = @counter + 1;END;Output
Section titled “Output”12345Explanation
Section titled “Explanation”In the given example, we declare a variable @counter as an integer and initialize it with the value 1. We then declare a WHILE loop that executes as long as @counter is less than or equal to 5.
Each time the loop executes, it prints the current value of @counter and then increments @counter by 1.
When @counter becomes 6, the condition of the WHILE loop fails (since 6 is not less than or equal to 5), and so the loop terminates.
As per the SQL Server output, we see that the PRINT statement has been executed 5 times, outputting the values from 1 through 5.