How to set a column alias as the result of a SQL query?

半城伤御伤魂 提交于 2019-12-10 12:27:21

问题


I need to use result of a SQL query to set column aliases. Please see below script and the result of the script I need to use it as column aliases.

select 
   convert(varchar,DATEADD(month, -12, dateadd(d,-day(convert(date,dateadd(d,-(day(getdate())),getdate()))),convert(date,dateadd(d,+1-(day(getdate())),getdate())))),107),
   convert(varchar,convert(date,dateadd(d,-day(convert(date,dateadd(d,-(day(getdate())),getdate()))),convert(date,dateadd(d,+1-(day(getdate())),getdate())))),107)

I need the answer for my question as soon as possible.


回答1:


Two solutions are described in the following link: Column alias based on variable

First solution:

  1. Set the alias in a variable
  2. Define the query as a nvarchar containing a reference to the variable.
  3. Execute the query using sp_executesql

    SET @column_alias = 'new_title'
    SET @sql = 'SELECT keycol, datacol AS ' + @column_alias + ' FROM Foo'
    
    EXEC sp_executesql @sql
    

Second solution: Rename the column after the execution of the query

    INSERT INTO Results
    SELECT keycol, datacol
    FROM Foo

    EXEC sp_rename 'Results.datacol', @column_alias, 'COLUMN' 


来源:https://stackoverflow.com/questions/37954284/how-to-set-a-column-alias-as-the-result-of-a-sql-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!