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
 Table name changes, how to grab the last 24 hours?

Author  Topic 

Ethel
Starting Member

4 Posts

Posted - 2014-05-30 : 09:47:33
Hi all,

My DB saves it's data into a table at the end of each day like:
'e4_event_20140530' where the last bit changes according to the date. So 30th May 2014 in this case.

What I am trying to do is query the last 24 hours. I know i can grab from 2 tables and do a 'between' with times but it means having to change table name and times in the query every time i run it. I'd just like to run it and for it to just fetch the last 24 hours at any point in time.

My DB outputs time like '2014-05-30 08:54:23'

Any help is most appreciated!

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2014-05-30 : 10:44:06
The ideal way, if you are allowed to do so, is to save the data into a SINGLE table. Since you have the time stamp, querying becomes very easy. Doing this way may make it appear that you have one huge table, and so querying would be difficult, but that is not the case - especially if you are allowed to index the time stamp column.

If you do not have the freedom to change the design, you would likely need to write a dynamic query that unions two tables based on the date - something like this:
DECLARE @sql NVARCHAR(4000), @tbl1 VARCHAR(64), @tbl2 VARCHAR(64);
SET @tbl1 = 'e4_event_'+CONVERT(VARCHAR(8),GETDATE(),112);
SET @tbl2 = 'e4_event_'+CONVERT(VARCHAR(8),DATEADD(dd,-1,GETDATE()),112);
SET @sql = 'SELECT * FROM '+@tbl1+' WHERE YourTimeColumn > ''' + CONVERT(NVARCHAR(32),DATEADD(dd,-1,GETDATE()),126) + ''''
+ 'UNION ALL ' +
'SELECT * FROM '+@tbl2+' WHERE YourTimeColumn > ''' + CONVERT(NVARCHAR(32),DATEADD(dd,-1,GETDATE()),126) + ''''
EXEC (@sql);
This is probably not the best way even for dynamic queries. You should parameterize it and use sp_executesql.
Go to Top of Page

Ethel
Starting Member

4 Posts

Posted - 2014-06-02 : 04:02:48
Hi, many thanks for the reply! It was most helpful :)

I'll look into sp_executesql and have a play.
Go to Top of Page
   

- Advertisement -