Home >> FAQs/Tutorials >> SQL Server FAQ
SQL Server FAQ - WHILE - Statement Structure for Loops
(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
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);
-- 2000 is a leap year!
(Continued on next topic...)
- How To Use "IF ... ELSE IF ... ELSE ..." Statement Structures?
- How To Use "BEGIN ... END" Statement Structures?
- How To Use WHILE Loops?
- How To Stop a Loop Early with BREAK Statements?
- How To Skip Remaining Statements in a Loop Block Using CONTINUE Statements?