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:
- 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.
Previous article: IF . ELSE command in SQL Server
Next article: FOR loop in SQL Server
You should read it
Maybe you are interested
What is Large Action Model (LAM)? SpaceX's Crew Dragon spacecraft successfully assembled with the ISS station, completely automated Will NASA partner with Tesla to create the most unprecedented lunar exploration vehicle? SpaceX is about to blow up a tens of millions of dollars worth of boosters on the Atlantic Life is amazing: The process of transforming from a living cell to a perfect living organism in just 6 minutes NASA announces a stunning series of GIF images that capture the historic moments of the aerospace industry