SQL Server Performance

Columns from Variables

Discussion in 'General DBA Questions' started by jordnlvr, Oct 6, 2005.

  1. jordnlvr New Member

    How can I use a variable as a column name?

    I am building a temp table, and 3 of the column names are derived based on the date.
    How can I get Yr2005, Yr2004 and Yr2003 based on current year and have it like this...

    DECLARE @year VARCHAR(6)
    SET @year = 'YR' + getDate() (yes I do the convert here, just saving time)

    SELECT something AS @year
    FROM #temptablewhatever

  2. Jon M Member

    Try this:

    declare @vyear char(6)
    set @vyear='YR'+ltrim(str(year(getdate())))

    exec('select ' +@vyear+' from #temptablewhatever')

    Jon M

Share This Page