Naming A column Dynamically

Manish Papreja 61 Reputation points
2022-07-01T04:07:19.553+00:00

Dear Experts

I have a simple query i.e. SELECT '100' as Sales2021,'200' as Sales2022

I want to name columns in above query dynamically as follows:-

SELECT
'100' as Concat('Sales',YEAR(GETDATE())-1)
,'200' as concat('Sales',YEAR(GETDATE()))

Is it possible? Is there any other way to achieve the above objective? Thanks in advance for your help.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
SQL Server | Other
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Anurag Sharma 17,636 Reputation points
    2022-07-01T04:33:08.887+00:00

    Hi @Manish Papreja , welcome to Microsoft Q&A forum.

    Please try below query:

    DECLARE @sql VARCHAR(1000);  
    SET @sql = 'SELECT   
        ''100'' AS ' + Concat('Sales',YEAR(GETDATE())-1) + ',  
        ''200'' AS ' + concat('Sales',YEAR(GETDATE()))  
    PRINT @sql  
    EXEC (@sql)  
    

    Reference: dynamic alias in T-SQL query

    Please let us know if this helps or else we can discuss further.

    ----------

    If answer helps, you can mark it 'Accept Answer'


  2. Olaf Helper 47,581 Reputation points
    2022-07-01T05:20:53.847+00:00

    I want to name columns in above query dynamically as follows:-

    With plain SQL it's not possible and don't make much sense; how should the client consuming the data should guess the column name?
    That's not how SQL works.


  3. Erland Sommarskog 128.6K Reputation points MVP Volunteer Moderator
    2022-07-01T21:33:43.877+00:00

    Yes, you can do this, although it is a bit bulky. You need to create a temp table with fixed names. Then you can rename the columns with sp_rename.

    I have an example here: https://www.sommarskog.se/dynamic_sql.html#dyncolaliases that you can work from.

    In many cases, though, it is better to deal with this client side.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.