Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Database Zone ·
Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

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.


Get comfortable using NoSQL in a free, self-directed learning course provided by RavenDB. Learn to create fully-functional real-world programs on NoSQL Databases. Register today.

Topics:
java ,sql ,sql server ,tips and tricks ,tools & methods

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}