-1

可能重复:
两个日期之间的月份

我有日期范围现在[start date] = '2012-09-01'[finish date] = '2014-01-01'
我需要显示两个日期之间的月份..使用单个选择语句

Expected Output :          
9
10
11
12
1
2
3
.
.
.
12
1

我怎样才能做到这一点?

4

2 回答 2

2
DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME;

SELECT   @StartDate = '20120901'        
        ,@EndDate   = '20140101';

;WITH MONTHS (date)
AS
(
    SELECT @StartDate
    UNION ALL
    SELECT DATEADD(MONTH,1,date)
    FROM MONTHS
    WHERE DATEADD(MONTH,1,date)<=@EndDate
)
SELECT MONTH(date) AS MONTH FROM MONTHS

结果:

MONTH
-----------
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
1

(17 row(s) affected)

编辑:根据您更新的要求,您可以使用以下查询实现此目的:

DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME;

SELECT   @StartDate = '20120901'        
        ,@EndDate   = '20140101';


SELECT  MONTH(DATEADD(MONTH, x.number, @StartDate)) AS Months
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate);

结果:

Months
-----------
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
1

(17 row(s) affected)
于 2012-09-11T04:45:43.143 回答
0

您还可以使用表变量:

DECLARE @startdt DATETIME, @enddt DATETIME
SELECT @startdt =  '2012-09-01', @enddt =  '2014-01-01'

DECLARE @Months TABLE (Months INT)

INSERT INTO @Months VALUES (MONTH(@startdt))
WHILE @startdt < @enddt
BEGIN
 SET  @startdt = DATEADD(MONTH,1,@startdt)
 INSERT INTO @Months VALUES (MONTH(@startdt))
END

SELECT * FROM @Months
于 2012-09-11T05:15:25.883 回答