WHILE loop in SQL Server

The WHILE loop is used if you want to run a code repeatedly when the given condition returns TRUE. Let's find out how to use WHILE in SQL Server with Network Administrator.

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:

  1. Use the WHILE loop statement when you are unsure of the number of times you want to execute.
  2. 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).
  3. See the command BREAK to exit the WHILE loop soon.
  4. See also the CONTINUE statement to restart the WHILE loop from the beginning.

Chart WHILE loop

WHILE loop in SQL Server Picture 1WHILE loop in SQL Server Picture 1

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.

Previous article: IF . ELSE command in SQL Server

Next article: FOR loop in SQL Server

5 ★ | 2 Vote