Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Dynamic Table Query

Author  Topic 

ProEdge
Yak Posting Veteran

64 Posts

Posted - 2007-07-19 : 17:56:58
I have a list of table names in a table. I'd like to be able to select from one of these tables based on a condition provided. I have my query in a stored procedure which expects a paramater called @Flag. My procedure works similar to this:
SELECT m.Column1, m.Column2
FROM myTable m
INNER JOIN (SELECT TableName FROM TableList WHERE Flag = @Flag) t ON m.ID = t.ID
Of course when I run this it fails. How can I create a dynamic query that will let me do this?

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2007-07-19 : 17:58:56
You'll need to use dynamic SQL.

Tara Kizer
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

ProEdge
Yak Posting Veteran

64 Posts

Posted - 2007-07-19 : 18:04:19
I figured I would but I don't have a clue how to start it. Could you provide a sample or link?
Go to Top of Page

dinakar
Master Smack Fu Yak Hacker

2507 Posts

Posted - 2007-07-19 : 18:07:09
This will be worth the time spent: http://www.sommarskog.se/dynamic_sql.html

Dinakar Nethi
************************
Life is short. Enjoy it.
************************
http://weblogs.sqlteam.com/dinakar/
Go to Top of Page

ProEdge
Yak Posting Veteran

64 Posts

Posted - 2007-07-19 : 18:07:53
Thanks.
quote:
Originally posted by dinakar

This will be worth the time spent: http://www.sommarskog.se/dynamic_sql.html

Dinakar Nethi
************************
Life is short. Enjoy it.
************************
http://weblogs.sqlteam.com/dinakar/

Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-07-19 : 18:09:10
http://www.sommarskog.se/dynamic_sql.html


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-07-19 : 18:09:26



Peter Larsson
Helsingborg, Sweden
Go to Top of Page
   

- Advertisement -