WHILE loop in SQL Server
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
5 ★ | 2 Vote
You should read it
May be interested
- FOR loop in SQL Serverthe for loop is often used to run a code repeatedly for the number of repetitions. however, in sql server there is no for loop.
- ASCII function in SQL Serverthe article will explore and guide you how to use the ascii () function in sql server.
- CHAR function in SQL Serverchar function in sql server is used to convert an integer expression into the corresponding character in ascii code.
- CHARINDEX function in SQL Serverthe charindex function in sql server is used to search for a substring within a large string starting from the specified position.
- CONCAT function in SQL Serverlearn how to use the concat () function in sql server to join two or more strings into a string.
- The '+' operator in SQL Serverlearn how to use the + operator in sql server to join two or more strings into a string.