2012-03-25 48 views
0

動態定義的列名我有這個SELECT聲明:由當前的日期在SQL Server

SELECT 
    ProjectId, 
    ProjectName,    
    D3 as "three month ago", 
    D2 as "two month ago", 
    D1 as "last month", 
    F0 as "current month", 
    F1 as "next month", 
    F2 as "next two month",   
FROM 
    View_Year_Forcast 

我想根據當月指定列名。

我有一個函數get_month_name獲取月份符號像(d1,d2,d3,f0 ..)並返回一個字符串,表示希伯來語中的月份名稱。

解決問題的最佳方法是什麼?

只是爲了記錄我試圖在SQL Server中做到這一點在存儲過程中

+2

你不能在T-SQL中做到這一點 - 你最好的選擇是打賭返回你現在查詢中的值,並**另外**返回這六個月中每個月的拼寫出的月份名稱。讓前端(網絡應用程序或其他)使用月份名稱而不是列名來處理實際顯示 – 2012-03-25 10:31:35

回答

0

可以使用動態SQL來做到這一點:

declare @month nvarchar(50) 
declare @sql nvarchar(1000) 

set @month = 'March' -- execute your `get_month_name` function here instead 

set @sql = 'select D3 as ' + @month + ' from View_Year_Forcast' 

exec sp_executesql @sql 

然而,動態SQL有它的問題。請參閱The Curse and Blessings of Dynamic SQL以獲得深入解釋。

所以,如果它在某種程度上有可能,我寧願使用動態SQL,但這樣做marc_s suggested in his comment
離開,因爲它是,除了返回月份的名稱,並讓客戶端顯示的月份名稱查詢正確的地方。

+0

@betite爲什麼你沒有選擇這個作爲答案? – 2016-02-25 19:50:06

相關問題