【问题标题】:Define column name dynamically by current date in SQL Server在 SQL Server 中按当前日期动态定义列名
【发布时间】:2012-03-25 09:34:24
【问题描述】:

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

【问题讨论】:

  • 您不能在 T-SQL 中执行此操作 - 最好的办法是返回您现在在查询中拥有的值,并且另外返回拼写出来的月份名称这六个月中的每一个。让前端(网络应用程序或其他)使用月份名称而不是列名称来处理实际显示

标签: sql-server columnname


【解决方案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 也有其问题。请参阅The Curse and Blessings of Dynamic SQL 以获得深入的解释。

因此,如果可能的话,我宁愿不使用动态 SQL,而是使用类似 marc_s suggested in his comment:
保持查询不变,另外返回月份名称,让客户端在正确的位置显示月份名称。

【讨论】:

  • @betite 你为什么没有选择这个作为答案?
猜你喜欢
  • 2013-10-26
  • 1970-01-01
  • 2020-09-21
  • 2013-10-12
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 2018-12-30
  • 1970-01-01
相关资源
最近更新 更多