SQL dynamic table names

I have a database with tables that are named with the following format

priceHistory200812
priceHistory200811
priceHistory200810 etc....

Based upon a month that is chosen I need to retrieve data from the tables for the previous six months. How would I accomplish this in MSSQL?
acsakanyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

richard_cristCommented:
Since the tables are probably "backups" of the data for that time period I am assuming that the fields in each of those tables are the same as the original data table.  If that is the case then use can use a JOIN clause to collect all the tables' data together into one query result and then use a WHERE clause against the joined data to find the records in question.

Is there a reason that the data was broken into separate tables based on month?  At first glance it sounds like a good idea, but as you have found it can complicate data retrieval.

0
acsakanyAuthor Commented:
I created a string with the "SELECT prichist200809 " in it and then I did an EXEC(@sqlString). This worked.
0
richard_cristCommented:
Building a dynamic string works for data within one specific table.  If you need data from more than one table month you can use the join or you can use the string method you mention above to query multiple tables and gather the data together manually.
If you found the answer yourself you can choose to have the question closed or if my comment helped you can accept my solution.  Let us know if you need any other information and I or others will try to help.   :)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.