行打印当月,然后是一年中的剩余月份

时间:2012-01-12 07:57:39

标签: sql sql-server database sql-server-2008 tsql

我想创建一个查询,以文本形式显示当前月份,然后在下一行中打印一年中的其余部分,直到打印出一年中的所有月份。

这有点难以解释所以我做了以下示例。我知道以下代码是荒谬的,但这是我知道用我目前的技能水平做到这一点的唯一方法。理想情况下,我还希望从打印整数转换月数来打印月份的字符值(因此1将是1月)。我知道我可以用一个案例/什么时候这样做,但我确信有一个更好的方式,我还没有接触过。

declare @currentmonth as int = datepart(month, getdate())
select
    @currentmonth
union
select
    @currentmonth +1
union
select
    @currentmonth +2
union
select
    @currentmonth +3
union
select
    @currentmonth +4
union
select
    @currentmonth +5
union
select
    @currentmonth +6
union
select
    @currentmonth +7
union
select
    @currentmonth +8
union
select
    @currentmonth +9
union
select
    @currentmonth +10
union
select
    @currentmonth +11

3 个答案:

答案 0 :(得分:4)

在SQL Server 2008+中,您可以使用此

SELECT v.i
FROM (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) v(i)
WHERE v.i>=MONTH(GETDATE())

答案 1 :(得分:3)

使用公用表表达式的机会(SQL Server 2005 +):

declare @adate datetime
set @adate = '2011-07-31'

;with clndr(m) as (
    select @adate
    union all
    select dateadd(month, 1, m)
    from clndr
    where datepart(year, dateadd(month, 1, m)) = datepart(year, @adate)
)
select datename(month, m)
from clndr

答案 2 :(得分:1)

使用Common表表达式,您可以轻松编写代码

    DECLARE @currentmonth INT
    SET @currentmonth=datepart(month, getdate())
    ;WITH CTE AS
    (SELECT @currentmonth AS currentmonth 
       UNION ALL 
     SELECT currentmonth +1 FROM CTE WHERE currentmonth <10
    )

    SELECT * FROM CTE
相关问题