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

Picture 1 of WHILE loop in SQL Server

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

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile