Column name as variable

  • Dear all,

    In a SQL-Script I want to use the column name as a variable, but a do not know the correct syntax. Example:

    Declare @var1 char(2)

    Set @var1 = 'xy'

    Select [@var1] from table_ab

    Can anyone help? Many thanks

    urs

  • Try this.

    Declare @var1 char(2)

    Set @var1 = 'xy'

    EXEC('Select ' + @var1 + ' from table_ab')

     

     

  • The correct systax is:

    Declare @var1 char(2)

    Set @var1 = 'xy'

    Select @var1 as Var1 from table_ab

  • that is not the correct syntax; the dynamic SQL Jon posted is the correct solution.

    your SQL would return 'xy' for every row in the table table_ab, where Jon's statement would return the Value stored in the column xy for the table table_ab.

    ie: results:

    Var1                          

    ------------------------------

    xy

    xy

    xy

    xy

    ...

    (476 row(s) affected)

    instead of

    xy

    ------------------------------

    149.65

    337.24

    959.33

    ...

    (476 row(s) affected)

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Guys you forgot the most important question to ask :

    Why do you want to use dynamic sql??

    Did you ever read this?

    The Curse and Blessings of Dynamic SQL

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

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