Dynamic column name?

  • Hi,

    I have a variable (date), that I want to use as a column header. Is this possible?

    Regards,

    Jason

  • Out of interest, can you explain why you need this?

    Should be easy enough via some dynamic SQL - not sure it will be possible otherwise.

    If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.

  • If you mean, creating a column that has a name which is a specific date, then yes it is possible by using dynamic sql (formating of the name may be an issue).

    However, it is an odd thing to require - why do you want to create such a specific column?

    Steve Hall
    Linkedin
    Blog Site

  • not sure about your exact problem.

    can't you use "AS" in your select statement ?

    select column as Date from ...

  • Yes you can.

    Just use a dynamic query. Something like this

    DECLARE @SQL_string AS varchar(200)

    DECLARE @Column_Name AS varchar(20)

    SET @Column_Name = 'Customer_Number'

    SET @SQL_string = 'SELECT CST_Num AS ' + @Column_Name + ', ' + CHAR(13) +

    'Revenue, Cost FROM CST_REV_TABLE'

    EXEC (SCR_TC_PREP)

    Good Luck!


    Jacob Milter

  • Ooops!

    Just realized that you need to use date variabe... 🙂

    Here it is:

    DECLARE @SQL_string AS varchar(200)

    DECLARE @Column_Name AS varchar(20)

    DECLARE @Date_Value AS Datetime

    SET @Date_Value = GETDATE()

    SET @Column_Name = 'Customer_Number'

    SET @SQL_string = 'SELECT CST_Num AS ' + @Column_Name + ', ' + CHAR(13) +

    'Revenue AS ' + 'Revenue_As_OF_' + REPLACE(CONVERT(VARCHAR(10),GETDATE(),101),'/','') + CHAR(13) +

    ', Cost FROM CST_REV_TABLE'

    --EXEC (@SQL_string)

    PRINT (@SQL_string)


    Jacob Milter

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply