Using a variable to reference a table name in T-SQL and accessing the resultant temporary table.

Posted on 2009-12-22
Last Modified: 2012-05-08
I have constructed a string of dynamic SQL which concatenates a select statement with a variable containing the name of the table I wish to interrogate.  This works fine and I can see the results clearly.  My problem is that I need to store the results of my query in a temporary table (which I've called #temp1)  in order to further manipulate the data; the 'select into' statement works fine, but the following query is failing with the message 'Invalid object name #temp1'.  Does anybody have a solution which would enable me to access the temporary table please?  Perhaps an alternative way of declaring/setting/using a variable as a table name?
Question by:Suelowe
    LVL 14

    Accepted Solution


    Author Closing Comment

    Many thanks for the quick response ajitha75.  I see I'm not the first to ask this particular question!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Introduction Hopefully the following mnemonic and, ultimately, the acronym it represents is common place to all those reading: Please Excuse My Dear Aunt Sally (PEMDAS). Briefly, though, PEMDAS is used to signify the order of operations (http://en.…
    Confronted with some SQL you don't know can be a daunting task. It can be even more daunting if that SQL carries some of the old secret codes used in the Ye Olde query syntax, such as: (+)     as used in Oracle;     *=     =*    as used in Sybase …
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now