WHILE loop
Using While loop
Section titled “Using While loop”The WHILE loop can be used as an alternative to CURSORS. The following example will print numbers from 0 to 99.
DECLARE @i int = 0; WHILE(@i < 100) BEGIN PRINT @i; SET @i = @i+1 ENDWhile loop with min aggregate function usage
Section titled “While loop with min aggregate function usage”DECLARE @ID AS INT;
SET @ID = (SELECT MIN(ID) from TABLE);
WHILE @ID IS NOT NULLBEGIN PRINT @ID; SET @ID = (SELECT MIN(ID) FROM TABLE WHERE ID > @ID);ENDRemarks
Section titled “Remarks”Using a WHILE loop or other iterative process is not normally the most efficient way to process data in SQL Server.
You should prefer to use a set-based query on the data to achieve the same results, where possible