DO... WHILE and REPEAT... UNTIL Loops in MS SQL

Introduction

When I am looking for a forum post related to SQL Server, one of the junior professional is asking how to use a DO…WHILE loop is MS SQL Server. Several people wrote their opinion related to it. Everyone is saying to use WHILE loop and some of them suggesting with T-SQL structure of CURSOR with WHILE LOOP.

Obviously, when a junior professional is learning MS SQL server, the question in mind arises: is there DO… WHILE, REPEAT … UNTIL loop present in MS SQL Server as there is in C or C++ etc?

No one is answering directly on the forum whether we can use DO… WHILE or REPEAT … UNTIL in MS SQL Server or NOT. If yes, how can we implement them?

DO… WHILE in MS SQL Sever

First we look at the algorithm of DO… WHILE.

SET X = 1

DO

 PRINT X

 SET X = X + 1

WHILE X <= 10 

Now we try to implement it in MS SQL Server.

DECLARE @X INT=1;

WAY:  --> Here the  DO statement

  PRINT @X;

  SET @X += 1;

IF @X<=10 GOTO WAY; --> Here the WHILE @X<=1 


REPEAT… UNTIL

First we look at the algorithm of REPEAT... UNTIL

SET X = 1

REPEAT

  PRINT X

  SET X = X + 1

UNTIL X > 10 

Now we try to implement it in MS SQL Server

DECLARE @X INT = 1;

WAY:  -- Here the REPEAT statement

  PRINT @X;

  SET @X += 1;

IFNOT(@X >1 0) GOTO WAY; -- Here the  UNTIL @X>10 


So we see that it is possible, but a little complicated… So most developers prefer the WHILE loop in MS SQL Server.


 

 

 

 

Top