Example of WHILE Loop in SQL Server

Here is a simple example of WHILE Loop in SQL Server:

DECLARE @counter1 INT
SET @counter1 = 1
WHILE (@counter1 < 6) BEGIN PRINT @counter1 SET @counter1 = @counter1 + 1 END GO

while_loop_sql_server

You can use BREAK and CONTINUE statements with IF...ELSE to control the execution of the WHILE loop:

DECLARE @counter1 INT
SET @counter1 = 1
WHILE (@counter1 < 6) BEGIN PRINT @counter1 SET @counter1 = @counter1 + 1 IF @counter1 = 3 BREAK ELSE CONTINUE END GO

while_loop_break_continue_sql_server