Непонятно, что вы действительно хотите делать внутри цикла, но вот как выполнить цикл и сохранить месяц во временной таблице:
CREATE TABLE #temp(mon int);
Declare @StartDate DATETIME = '2016-09-01',
@EndDate DATETIME = '2017-01-31'
-- Now you have 12 months and you can use below query to loop through each month starting from January
WHILE (@StartDate <= @EndDate)
BEGIN
DECLARE @Month INT = Month(@StartDate) -- At the start of loop @Month is equal to 9
-- Save @Month to temp table in each repeat
INSERT INTO #temp (mon)
SELECT @Month;
SET @StartDate = DATEADD(MONTH, 1, @StartDate); -- this line adds 1 value to @Month after first loop @Month will be 10
END
Если вы хотите запустить цикл с @StartDate
(сентябрь 2016 г.), а затем завершите его @EndDate
(январь 2017 г.). Приведенный выше запрос выполняет точно такой же процесс. Но если вы хотите изменить @StartDate
на 2016-01-01
и @EndDate
на 2016-12-31
, используйте следующий запрос:
CREATE TABLE #temp(mon int);
Declare @StartDate DATETIME = DATEADD(MONTH, -8, '2016-09-01'); -- It will set @StartDate to '2016-01-01'
Declare @EndDate DATETIME = DATEADD(MONTH, 11, DATEADD(YEAR, -1, '2017-01-31')); -- It will set @EndDate to '2016-12-31'
-- Now you have 12 months and you can use below query to loop through each month starting from January
WHILE (@StartDate <= @EndDate)
BEGIN
DECLARE @Month INT = Month(@StartDate) -- At the begining @Month is equal to 1
-- Save @Month to temp table in each repeat
INSERT INTO #temp (mon)
SELECT @Month;
SET @StartDate = DATEADD(MONTH, 1, @StartDate); -- this line adds 1 value to @Month after first loop @Month will be 2
END