Link to home
Start Free TrialLog in
Avatar of acsakany
acsakany

asked on

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?
Avatar of richard_crist
richard_crist
Flag of United States of America image

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.

Avatar of acsakany
acsakany

ASKER

I created a string with the "SELECT prichist200809 " in it and then I did an EXEC(@sqlString). This worked.
ASKER CERTIFIED SOLUTION
Avatar of richard_crist
richard_crist
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial