Is it possible to build this kind of dynamic query?

Posted on 2005-05-03
Last Modified: 2011-09-20
Hi all!
   This is a hard one ( well i think its hard or impossible ),
I would like to build a dynamic query from the value within a table.

ID             value
1              'tablefoo'

FirstName        LastNAme
'Mike'              'Mike'

Now i would like to build a query like
SELECT * FROM tablefoo <-- but this value has to come from a previous SELECT
so i would like to do something like
SELECT * FROM (SELECT value FROM TAbleQuery WHERE ID = 1) <-- the result of that select would be 'tablefoo'

is it possible
Question by:Chadak
    1 Comment
    LVL 28

    Accepted Solution

    DECLARE @tableName VARCHAR(100)

    SELECT @tableName = Value
    FROM TableQuery
    WHERE ID = 1

    SET @SQL = 'SELECT * FROM ' + @tableName
    EXEC (@SQL)

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
    The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
    Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
    Via a live example, show how to setup several different housekeeping processes for a SQL Server.

    730 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

    17 Experts available now in Live!

    Get 1:1 Help Now