Wednesday, October 22, 2008

How to use the while loop using sql server

How to use the while loop using sql server

To start with the discussion we need a counter variable with an int DataType that would define the limit to where the loop will stop. In my case I named my counter variable as TotalMonths and
assigned it with a value of 12.

Declare @TotalMonths as int
set @TotalMonths = 12

-- The While statement is almost the same as the usual programming
-- concept for the while statement. All we need is the logic as to how the
-- loop takes place.
-- In my case I wanted to begin my loop by stating that TotalMonths should be
-- greater than zero before it executes the loop..

While @TotalMonths>0

-- We need to have the begin and end statement after the condition in order to
-- set the scope of the while loop. Hence, if we try to remove the begin/end in the loop,
-- we will notice that the query will have an infinite loop.
begin
-- Here we create the statement that we wanted to do if the condition of the
-- while statement is true.
print datename(mm,(dateadd(mm,-@TotalMonths,(1))))

-- The most important thing on the while loop, is to create a loop iterator to avoid
-- infinite loops.
set @TotalMonths = @TotalMonths - 1
end

Script:
Declare @TotalMonths as int
set @TotalMonths = 12

While @TotalMonths>0
begin
print datename(mm,(dateadd(mm,-@TotalMonths,(1))))
set @TotalMonths = @TotalMonths - 1
end


This results:

January
February
March
April
May
June
July
August
September
October
November
December

No comments: