2014-01-26 35 views
1

我想在查詢中顯示所有月份名稱,月份數量和年份。在sql server中如何獲得從給定日期開始的所有月份和年份

假設我定的日期是否

@日期=」 2003-03-01'

我的期望了賣出期權波紋管:

enter image description here

幫我修復我的bellow sql語法。

DECLARE @Date DATE = '2003-03-01', 
     @inc INT = 0 
;with cte as 
(
    select 
    @inc AS Inc, 
    DATENAME(mm,@Date) AS [MonthName], 
    DATEPART(mm,@Date) AS [MonthNumber], 
    DATEPART(yy,@Date) as [MonthYear] 
    UNION ALL 
    select 
    inc+1, 
    DATENAME(mm,DATEADD(mm,inc+1,@Date)), 
    DATEPART(mm,DATEADD(mm,inc+1,@Date)), 
    DATEPART(yy,@date) 
    FROM cte 
    where inc < 12 
) 
select [MonthName],[MonthNumber],[MonthYear] from cte 

如果有任何疑問請提出,任何類型的建議將是可以接受的。感謝高級。

回答

1

是否這樣?

DECLARE @Date DATE = '2003-03-01', 
     @inc INT = 0 
;with cte as 
(
    SELECT Inc    = @inc     
      ,[MonthName]  = DATENAME(mm ,@Date) 
      ,[MonthNumber] = DATEPART(mm ,@Date) 
      ,[MonthYear]  = DATEPART(yy ,@Date) 
    UNION ALL 
    SELECT inc + 1 
      ,DATENAME(mm ,DATEADD(mm ,inc + 1 ,@Date)) 
      ,DATEPART(mm ,DATEADD(mm ,inc + 1 ,@Date)) 
      ,CASE WHEN [MonthNumber] = 12 THEN [MonthYear] + 1 ELSE [MonthYear] END 
    FROM cte 
    WHERE inc < 12 
) 
select [MonthName],[MonthNumber],[MonthYear] from cte 

雖然這可能是一個更簡單的模式;

DECLARE @Date DATE = '2003-03-01' 
;WITH MoreSimple as 
(
    SELECT [MonthName] = DATENAME(mm ,@Date) 
      ,[MonthNumber] = DATEPART(mm ,@Date) 
      ,[MonthYear] = DATEPART(yy ,@Date) 
      ,NextRow  = DATEADD(MONTH, 1, @Date) 
    UNION ALL 
    SELECT DATENAME(mm ,NextRow) 
      ,DATEPART(mm ,NextRow) 
      ,DATEPART(yy ,NextRow) 
      ,DATEADD(MONTH, 1, NextRow) 
    FROM MoreSimple 
) 
SELECT TOP(100) 
     [MonthName] 
     ,[MonthNumber] 
     ,[MonthYear] 
FROM MoreSimple 
OPTION(MAXRECURSION 0) 


---------- 
0

您獲得年份的表達僅使用原始日期。使用dateadd()結果代替:

DECLARE @Date DATE = '2003-03-01', 
     @inc INT = 0 
;with cte as 
(
    select 
    @inc AS Inc, 
    DATENAME(mm,@Date) AS [MonthName], 
    DATEPART(mm,@Date) AS [MonthNumber], 
    DATEPART(yy,@Date) as [MonthYear] 
    UNION ALL 
    select 
    inc+1, 
    DATENAME(mm,DATEADD(mm,inc+1,@Date)), 
    DATEPART(mm,DATEADD(mm,inc+1,@Date)), 
    DATEPART(yy, DATEADD(mm,inc+1,@Date)) 
    FROM cte 
    where inc < 12 
) 
select [MonthName],[MonthNumber],[MonthYear] from cte 
+0

Gordon Linoff,感謝您的回覆,我也想獲取月開始日期結束日期 – shamim

相關問題