Home » SQL For Programmers » SQL WHILE – SQL For Programmers

SQL WHILE – SQL For Programmers

The IF statement we looked at on Tuesday was pretty tame compared to the WHILE construct.

Actually, the main thing you need to keep in mind is that WHILE is all you have.  There is no such thing as a FOR loop or a DO WHILE loop.  So, you have to force WHILE to do those for you.

The basic syntax of WHILE looks like this:

DECLARE @someString as VARCHAR
WHILE @someString='ABC'
  BEGIN
   SELECT * FROM someTABLE
   SELECT * FROM someOtherTABLE
  END

So if you want a FOR/NEXT loop, you’ll need to write:

DECLARE @someInt as int
SET @someInt = 0
WHILE @someInt < 20
  BEGIN
   /* useful code here */
   SET @someInt = @someInt + 1
  END

and a DO WHILE loop would be something like:

DECLARE @someInt as int
SET @someInt = 0
WHILE @someInt = 0
  BEGIN
   /* useful code here */
   IF *some exit condition */
     SET @someInt = 1
  END

Once you learn to substitute those constructs for your normal FOR/NET or DO WHILE code, it becomes rather easy to deal with.

Now if they’d just replace BEGIN with { and END with } I think I could live with this.

 

Other post in SQL For Programmers

Related Post

  • SQL For Programmers – Finding a StringSQL For Programmers – Finding a String Many times in our queries, we aren't looking for an exact match.  We are looking for one string that exists in another.  There are a couple statements available to us that will allow us […]
  • SQL for .NET Programmers–The BookSQL for .NET Programmers–The Book Today, I finally announce the availability of my new book.  SQL For .NET Programmers.This book is based on the series of post I wrote in 2008.  If those post have been valuable to […]
  • Computed Columns Using LINQ to SQL ClassesComputed Columns Using LINQ to SQL Classes Last week we looked at the extension points Microsoft has wired into the LINQ to SQL classes and how they can be used to achieve some of the capabilities of the Business Logic Layer (BLL) […]
  • && vs & and | vs ||… What’s the difference?&& vs & and | vs ||… What’s the difference? It seems like such a trivial thing to be talking about but not knowing the difference between && vs & or || vs | can make a huge difference between working code and code that only seems […]
  • Response.Redirect() executes too soon on the Server.Response.Redirect() executes too soon on the Server. I've seen this question a couple of times in various situations. The first involves Javascript and the second involves server side code. Both are caused by a misunderstanding of what this […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer focusing on ASP.NET, C#, Node.js, JavaScript, HTML, CSS, BootStrap, and Angular.JS.Does your team need additional help in any of the above? Contact Dave today.

2 Pingbacks/Trackbacks