How to do a Select xx from

  • Hi,

    Hope that someone can help me on this one.

    I have a Local variable containing a tablename and would like to do a select from the table in the variable.

     

    Something like this: Select XX from @Variable

     

    /Henrik

  • Would you mind to look around a little?

    There is an answer on your question on the 1st page of this forum and couple of answers on the second page.

    Happy browsing.

    _____________
    Code for TallyGenerator

  • You will have to use dynamic SQL.

    exec('SELECT xx FROM ' + @Variable)

     

  • And, you need to be real careful if this comes anywhere near a GUI... think "SQL Injection".  Theres a huge amount of info on how to prevent it... do a search for "SQL Injection" on Google.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

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

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