LOOP

LOOP in SQL is a control structure used for executing a set of statements repeatedly until a certain condition is met. When used, LOOP executes the sequence of statements between its LOOP and END LOOP keywords. The loop will continue indefinitely until intentionally stopped with an EXIT statement, typically conditioned on a certain event or state.

Example

DECLARE
i NUMBER;
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
/

Output

1
2
3
4
5

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

DECLARE @counter INT;
SET @counter = 1;
WHILE @counter <= 5
BEGIN
PRINT @counter;
SET @counter = @counter + 1;
END;

Output

1
2
3
4
5

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.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.