Over a million developers have joined DZone.

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

· Database Zone

Sign up for the Couchbase Community Newsletter to stay ahead of the curve on the latest NoSQL news, events, and webinars. Brought to you in partnership with Coucbase.

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.


The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.

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

Published at DZone with permission of Joydeep Das, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}