Loops in SQL Server
In SQL Server, a loop is the technique where a set of SQL statements are executed repeatedly until a condition is met.
SQL Server supports the WHILE loop. The execution of the statements can be controlled from within the WHLE block using BREAK and CONTINUE keywords.
WHILE <condition>
SQL Statement | statement_block | BREAK | CONTINUEBoolean_expression : A boolean expression that returns TRUE or FALSE.
sql_statement | statement_block : A single or a group of SQL statements (statement block). Statement block should be enclosed with BEGIN and END keywords.
BREAK: Causes the flow to exit from the innermost WHILE loop. Statements after the END keyword are executed after the BREAK.
CONTINUE: Causes the WHILE loop to restart. It ignores all statements after the CONTINUE keyword.
While Loop
The following example uses the WHILE loop to print numbers.
DECLARE @i INT = 10;
WHILE @i <= 30
BEGIN
PRINT (@i);
SET @i = @i + 10;
END;The following displays the result in SSMS.