This SQL Server tutorial explains how to use the WHILE LOOP in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server, you use a WHILE LOOP when you are not sure how many times you will execute the loop body and the loop body may not execute even once.
Parameters or Arguments
condition: The condition is test each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated.
statements: The statements of code to execute each pass through the loop.
Pay attention to the following facts:
You would use a WHILE LOOP statement when you are unsure of how many times you want the loop body to execute.
Since the WHILE condition is evaluated before entering the loop, it is possible that the loop body may not execute even once.
See also the BREAK statement to exit from the WHILE LOOP early.
See also the CONTINUE statement to restart the WHILE LOOP from the beginning.