2012-09-11 51 views

回答

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 
+0

我是否可以通過單個select語句獲得它...而不使用臨時表 –

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)<[email protected] 
) 
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) 
+0

我可以通過單個select語句獲得它嗎?不使用臨時表 –

+0

@ user1416769查看更新後的答案。 – hims056

相關問題