In this post 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.
The syntax for the WHILE LOOP in SQL Server (Transact-SQL) is:
The condition is tested each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated.
The statements of code to execute each pass through the loop.
Let's look at an example that shows how to use a WHILE LOOP in SQL Server (Transact-SQL).
For example:
In this WHILE LOOP example, the loop would terminate once the @site_value exceeded 10 as specified by:
The WHILE LOOP will continue while @site_value = 10. And once @site_value is > 10, the loop will terminate.
You can also use a WHILE LOOP in a cursor.
For example:
In this WHILE LOOP example, the loop would terminate once the @@FETCH_STATUS no longer equals 0, as specified by: