SQL: While Loop

To repeat a block of code in SQL until a certain condition is reached, you can use a WHILE loop, like this:

--DECLARE your vars first
DECLARE @var1 INT
DECLARE @var2 INT
 
--the WHILE itself
WHILE @var1 > 10
     BEGIN
          @var2 = @var2 + @var1
          IF @var2 > 10
               BREAK
     END

The IF block will simply check @var2 until it is greater than 10, then it BREAKs the WHILE loop. Of course you can do a SELECT inside a WHILE, and almost anything else, but be sure you add some way to stop the loop or it will loop on and on forever and most likely crash your machine or at least cause trouble. Hooray Trouble!

, , , ,

Leave a Reply

You must be logged in to post a comment.