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
 General SQL Server Forums
 New to SQL Server Programming
 Dynamically change based on date

Author  Topic 

Petronas
Posting Yak Master

134 Posts

Posted - 2014-02-26 : 12:39:58
Hi,

I have to change the name of the history table dynamically to what is passed in the start date.
If @start_date= '1/1/2014' then it should be history_jan14
If @start_date ='02/01/2014' then it should be history_feb14 and so on.
Is there a way you can do it ?
I am using SQL Server 2008.

Code :

DECLARE @start_date datetime
DECLARE @end_date datetime


SET @start_date = '01/01/2014'
SET @end_date = '02/01/2014'


select switch_hose,COUNT(*) as 'switch_count'
from history_jan14 hj (nolock),
inner join gap_orders ga (nolock)
on hj.switch_id = ga.switch_id


Thanks ,
Petronas

kennejd
Starting Member

11 Posts

Posted - 2014-02-26 : 12:53:15
I have to say...I'm not sure your database design is quite right. One table should hold all items. Having said that, you could use dynamic sql to query your different tables based on an input parameter.
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2014-02-26 : 13:57:54
Agreed with Kennejd, that is a bad design.

One solution might be to create a view that unions all those history tables together, assuming they have a date column you can use to apply your range correctly.

Otherwise, as Kennejd mentioned, you'll have to use Dynamic SQL.

http://www.sommarskog.se/dynamic_sql.html
http://www.nigelrivett.net/SQLTsql/TableNameAsVariable.html
Go to Top of Page
   

- Advertisement -