WHILE
WHILE is a control flow statement in SQL that allows a part of the code to be executed repeatedly based on a specified Boolean condition. The WHILE loop continues executing the block of code it encompasses until the condition evaluates to 'false'.
Example
Output
Explanation
In the example provided, a variable @number
is initialized as 0
. The WHILE
loop continues executing the statements within as long as @number
is less than 5
. Inside the loop, @number
is incremented by 1
with each iteration. Consequently, the SQL script outputs the numbers from 1
to 5
, inclusively.
Example
Output
Explanation
The above SQL script initializes an integer counter and uses a WHILE loop to print the numbers from 1 to 10 incrementally. The loop continues until @intCounter is greater than 10.
Example
Output
Explanation
In the provided code example, an initial variable named num
is declared and set to 1. The WHILE loop starts and checks if num
is less than or equal to 5. If it is true, it outputs the value of num
and then increments num
by 1. This cycle continues until num
is greater than 5, causing the WHILE condition to fail and thus terminating the loop. The output, therefore, consists of number 1 to 5, each on a new line.