The WHILE loop (WHILE LOOP) is used if you want to run a code repeatedly when the given condition returns TRUE. The article will explain in detail how to use it with a clear syntax and example to make it easier to imagine WHILE in SQL Server.
Syntax
To use WHILE loop in SQL Server, we use the syntax as below:
WHILE dieukien / * commands to repeat * /
BEGIN
{. execute command when condition is TRUE .}
END;
Note:
- Use the WHILE loop statement when you are unsure of the number of times you want to execute.
- Since the WHILE condition is evaluated before entering the loop, the loop may not work once (when dieukien is FALSE, the loop will end immediately).
- See the command BREAK to exit the WHILE loop soon.
- See also the CONTINUE statement to restart the WHILE loop from the beginning.
Chart WHILE loop
For example
DECLARE @Number INT = 1;
DECLARE @Total INT = 0;
@Number WHILE <= 10
BEGIN
SET @Total = @Total + @Number;
SET @Number = @Number + 1;
END
PRINT @Total;
GO
In this example, the loop will not perform any time if at the beginning of @Number> 10, it only executes and maintains when variable <= 10. When the condition is exceeded (> 10), the loop will end End and continue executing the next statement.