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

Traditional relational databases weren’t designed for today’s customers. Learn about the world’s first NoSQL Engagement Database purpose-built for the new era of customer experience.

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.


Learn how the world’s first NoSQL Engagement Database delivers unparalleled performance at any scale for customer experience innovation that never ends.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}