如何进入年份和月份之间从年份和月份到使用sql的月份

时间:2014-09-16 11:48:04

标签: sql-server

MonthFROM  |  YearFROM  |  MonthTo | YearTO
---------------------------------------------
   02          2012          05       2012

输出应该是:

Month  Year
 02    2012
 03    2012
 04    2012
 05    2012

2 个答案:

答案 0 :(得分:1)

使用master..spt_values作为计数表(最多2047个月,否则使用另一个计数表):

DECLARE
  @MonthFROM int = 2,
  @YearFROM  int = 2012, 
  @MonthTo   int = 5,
  @YearTO    int = 2012

DECLARE
  @from datetime = dateadd(month, @MonthFROM-1, cast(@YearFrom as char(4)))
DECLARE
  @to datetime = dateadd(month, @MonthTO-1, cast(@YearTo as char(4)))

SELECT month(dateadd(m, number, @from)) Month, year(dateadd(m, number, @from)) Year
FROM
   master..spt_values
WHERE 
  type = 'P' and
  number <= datediff(month, @from, @to)

结果:

Month Year
2     2012
3     2012
4     2012
5     2012

答案 1 :(得分:1)

您可以使用CTE并将范围转换为日期时间以便于处理。

declare @tab TABLE (ID int,MonthFROM int,  YearFROM  int,  MonthTo int, YearTO int)
insert into @tab Select 1,2,2012,5,2012


;With CTE(Start,aEND) as
(
Select CAST(
           CAST(YearFROM AS VARCHAR(4)) +
           RIGHT('0' + CAST(MonthFROM AS VARCHAR(2)), 2) + '01'   
           AS DATETIME) as Start
      ,CAST(
           CAST(YearTo AS VARCHAR(4)) +
           RIGHT('0' + CAST(MonthTo AS VARCHAR(2)), 2) + '01'   
           AS DATETIME) as aEND
from  @tab   
Where ID=1

UNION ALL
Select DATEADD(MM,1,Start),aEND from CTE  Where DATEADD(MM,1,Start)<=aEND                   

)
Select DATEPART(MM,Start) as [Month],DATEPART(YY,Start) as [Year] from CTE