2012-01-12 150 views
3

我想查詢以文本形式顯示當前月份,然後在下列行中打印當年餘下年份,直到本年度的所有月份打印。行當前月份和當年剩餘月份

這有點難以解釋,所以我做了下面的例子。我知道下面的代碼是荒謬的,但這是我知道用我目前的技能水平來做這件事的唯一方法。理想情況下,我還想從打印一個整數轉換爲打印月份的字符值(因此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 

回答

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

簡單eleg螞蟻,謝謝你 – Codingo 2012-01-12 08:15:31

+0

@邁克爾很高興這有幫助。 – 2012-01-12 08:21:10

+0

此功能稱爲行構造函數。這是一個很棒的功能。然而,與常規方式相反,使用此功能完成的大量插入操作會受到性能影響。 [相關文章](http://connect.microsoft.com/SQLServer/feedback/details/508112/insert-performance-of-row-constructor-is-quiet-bad) – Animesh 2012-01-12 11:49:36

3

使用公用表表達式(SQL服務器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 
1

與普通表表達式可以輕鬆編寫代碼

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

複製另一個答案...真的嗎? – Codingo 2012-01-12 09:36:15

+0

@Michael你應該看到sql語句,然後做出這樣的評論。在SQL中唯一常見的是使用CTE,但邏輯完全不同 – praveen 2012-01-12 10:18:53

相關問題