How to set a column alias as the result of a SQL q

2019-06-14 19:49发布

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.

标签: sql alias
1条回答
不美不萌又怎样
2楼-- · 2019-06-14 20:38

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' 
查看更多
登录 后发表回答