循环基于参数值

时间:2015-12-18 19:37:31

标签: sql-server-2008 loops if-statement while-loop

我需要创建一个基于两个参数填充的临时表:

declare @Start date = '01/01/2015'
declare @End date = '12/31/2015'

临时表应该有一个列,可以捕获@Start和@End参数之间所有年份和月份的YYYYMM。

这是我到目前为止所拥有的。我想在201412停止它,然后在201501再次开始。相反,这个循环继续增加加1(我不想看到201413..so):

declare @Start date = '01/01/2014'
declare @End date = '12/31/2015'

declare @monthstart as int
declare @monthend as int
declare @increment as int

set @monthstart = (SELECT LEFT(CONVERT(varchar, @Start,112),6))
set @monthend = (SELECT LEFT(CONVERT(varchar, @End,112),6))

create table #datetemp  (RelevantYYYYMM int)
insert into #datetemp values (@monthstart)
set @increment = @monthstart


While @increment < @monthend
BEGIN 
set @increment = (select Max(RelevantYYYYMM) + 1 from #datetemp)
insert into #datetemp values (@increment)
set @increment = (select Max(RelevantYYYYMM) from #datetemp)
IF (select Max(RelevantYYYYMM) from #datetemp) > @monthend
Break
else 
continue
END

select * from #datetemp

1 个答案:

答案 0 :(得分:1)

您可以使用计数表并避免循环:

CREATE TABLE #datetemp (RelevantYYYYMM INT);

DECLARE @Start DATE = '01/01/2015', @End DATE = '12/31/2015';

WITH tally_table AS
(
  SELECT TOP 1000 rn = ROW_NUMBER() OVER(ORDER BY name) - 1
  FROM master..spt_values
)
INSERT INTO #datetemp(RelevantYYYYMM)
SELECT LEFT(CONVERT(varchar, DATEADD(month, rn, @Start),112),6)
FROM tally_table
WHERE YEAR(DATEADD(month, rn, @Start)) <= YEAR(@End)
  AND MONTH(DATEADD(month, rn, @Start)) <= MONTH(@End)

SELECT *
FROM #datetemp;

LiveDemo