1

我有这样的SELECT声明:

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 的存储过程中执行此操作

4

1 回答 1

1

使用动态 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 有其问题。有关深入解释,请参阅动态 SQL 的诅咒和祝福。

因此,如果可能的话,我宁愿使用动态 SQL,而是执行他的评论中建议的 marc_s之类的操作:
保留查询原样,另外返回月份名称,并让客户端在正确的位置显示月份名称。

于 2012-03-25T10:46:44.050 回答