WHILE (Transact-SQL)
The WHILE statement creates a loop that executes a Transact-SQL statement or a block of statements as long as the specified condition is true.
Syntax
WHILE <boolean_expression>
BEGIN
<transact-sql_statements>
END
Arguments
<boolean_expression>
An expression that returns TRUE or FALSE. If the expression returns TRUE, the statements inside the WHILE loop are executed. If the expression returns FALSE, the loop is exited.
<transact-sql_statements>
One or more Transact-SQL statements that are executed as long as the <boolean_expression> evaluates to TRUE.
Description
The WHILE loop continues to execute the statements in the loop as long as the specified boolean expression is true.
The condition is evaluated at the beginning of each loop iteration. If the condition is initially false, the statements inside the loop are never executed.
You can use BREAK to exit a WHILE loop, even if the boolean expression is still true. You can use CONTINUE to skip the rest of the current iteration and return to the evaluation of the WHILE condition.
Example
The following example creates a loop that prints numbers from 1 to 5.
DECLARE @Counter INT;
SET @Counter = 1;
WHILE @Counter <= 5
BEGIN
PRINT 'Counter is: ' + CAST(@Counter AS VARCHAR);
SET @Counter = @Counter + 1;
END;
See Also
Note
Ensure that the condition in the WHILE loop eventually becomes false to avoid an infinite loop.