Select Column contents from variable

  • Hello everyone,

    I have a variable called @ColumnName which contains the name of a column (ie ProductName). How would I go about selecting the contents of the column and not the column name itself?

    ie

    SELECT @ColumnName

    will return 'ProductName'

    instead of the data in the field ProductName.

    Please note that I want to avoid storing the entire sql statement in a string and using an exec statement since this SELECT statement I'm creating is the second part of a INSERT INTO statement.

    Thanks,

    Strick

  • You can't. The compiler will return the scalar value stored in productname. You can't make part of the statement dynamic and part static.

    Why not just write the queries you need?

  • Hi, Thanks,

    Reason I can't write the queries I need is because the fieldname changes based on the variable making it a little more dynamic. What I have works great except for getting the contents of the variable instead of the variable itself. I know VB has a call by object function. I was thinking that T-SQL has something similiar

  • This seriously sounds like a highly questionable approach.

    However, if you really want to do it, you need to use dynamic SQL:

    DECLARE @mySQL nvarchar(max)

    SET @mySQL = 'SELECT ' + @Column + ' FROM TableX'

    exec sp_executesql @mySQL

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

Viewing 4 posts - 1 through 3 (of 3 total)

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