Home >> FAQs/Tutorials >> SQL Server FAQ

SQL Server FAQ - WHILE - Statement Structure for Loops

By: FYIcenter.com

(Continued from previous topic...)

How To Use WHILE Loops?

WHILE statement structure is used to create a loop to execute a statement or a statement block repeatedly under a specific condition. WHILE statement structure has the following syntax formats:

1. Loop with a single statement
WHILE condition repeating_statement

2. Loop with a statement block
WHILE condition BEGINE
   statement_1
   statement_2
   ...
   statement_n
   END

The tutorial exercise below shows you how to use a WHILE statement structure to execute a statement block repeatedly:

-- Counting number of days in 2000
DECLARE @date DATETIME;
DECLARE @count INT;
SET @date = '2000-01-01'; 
SET @count = 0;
WHILE DATEPART(YEAR, @date) = 2000 BEGIN
   SET @count = @count + 1;
   SET @date = DATEADD(DAY, 1, @date);
   END
SELECT @count;
366
-- 2000 is a leap year!

(Continued on next topic...)

  1. How To Use "IF ... ELSE IF ... ELSE ..." Statement Structures?
  2. How To Use "BEGIN ... END" Statement Structures?
  3. How To Use WHILE Loops?
  4. How To Stop a Loop Early with BREAK Statements?
  5. How To Skip Remaining Statements in a Loop Block Using CONTINUE Statements?

Related Articles:

More...


Other Tutorials/FAQs:

More...


Related Resources:

More...


Selected Jobs:

More...