DO WHILE and WHILE loop in SQL Server

Last Reply one year ago By dharmendr

Posted one year ago

hi all

give some scenarios for do while and and while loop conditions in sql server.

thanks and regards

siddu

You are viewing reply posted by: dharmendr one year ago.
Posted one year ago

Hi siddangoud,

SQL Server doesn't have a DO WHILE loop construct, but same behaviour can be achieved using a WHILE loop as shown by the below example.

SQL

DECLARE @Counter INT 
SET @Counter = 1
WHILE (@Counter <= 4)
BEGIN
	PRINT @Counter
	SET @Counter = @Counter  + 1 
END

With BREAK statement

DECLARE @Counter INT 
SET @Counter = 1
WHILE(1 = 1)
BEGIN
PRINT @Counter
SET @Counter = @Counter  + 1    
IF(@Counter > 4)
	BREAK;         
END

Output

1

2

3

4

With CONTINUE statement

DECLARE @Counter INT 
SET @Counter = 0
WHILE ( @Counter <= 4)
BEGIN
    SET @Counter = @Counter  + 1 
 
    IF(@Counter = 2)
        CONTINUE;
    PRINT @Counter 
END

Output

1

3

4

5