在sql server中如何从给定日期获取所有月份和年份

时间:2014-01-26 14:24:06

标签: sql sql-server common-table-expression

我想在查询中显示所有月份名称,月份编号和年份。

假设我的指定日期是

  

@ date ='2003-03-01'

我想要的输出是低于:

enter image description here

帮我修复我的轰鸣声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

如果有任何疑问请询问,任何类型的建议都是可以接受的。谢谢你提前。

2 个答案:

答案 0 :(得分: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)


----------

答案 1 :(得分: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