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)
 SQL Agent - Delete Records older than 24 Hours?

Author  Topic 

mattboy_slim
Yak Posting Veteran

72 Posts

Posted - 2009-02-27 : 14:59:18
First off, let me begin by saying that I'm new to T-SQL (like two hours new). Now that we have that out of the way, let me get to the meat of my question:

I want to use a SQL Server Agent (2005) job to delete records from a table that are more than 24 hours old.
Database Name: db_volumetest
Table Name: tb_syslog
Field Names: f_syslogID, f_timestamp

I want to delete records where 'f_timestamp' is less than midnight(when the script runs) minus 24 hours.

In SQL Server Agent, I have created a new "job", and the first "step" within the job contains the following command:
DELETE FROM tb_syslog
WHERE f_timestamp < '02/26/2008 12:01:00 AM';


Unfortunately, the above does not work if I run the job, but beyond that I need to figure out how to get the logic to replace the statically-entered value above to a dynamic value of "NOW minus 24 hours".

Thanks in advance,
Matt

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-02-27 : 15:02:11
Try this:

DELETE FROM tb_syslog
WHERE f_timestamp < DATEADD(Day, DATEDIFF(Day, 0, GetDate())-1, 0)


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

mattboy_slim
Yak Posting Veteran

72 Posts

Posted - 2009-02-27 : 15:27:50
Thanks very much, that appears to have worked exactly like I needed it. I knew I picked the right forum for support!

I'll be back about a thousand times more over the next few months as I convert "cURL" scheduled batch files to SQL jobs.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-02-27 : 15:29:39
You're welcome, glad it worked for you.

If you know that the DELETE statement will run at midnight, then it can simply be:

DELETE FROM tb_syslog
WHERE f_timestamp < GETDATE()-1

The other part of it removes the time portion of GETDATE() in case you run it sometime other than midnight.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -