Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Daily SQL Task to delete contents from a table

Hey I was wondering how I could set up a clean up task on a particular table to delete contents thats lets say a week old.

I am using SQL Server 2005

like image 911
StevieB Avatar asked Oct 01 '10 14:10

StevieB


2 Answers

In SQL Server Management Studio, expand the SQL Server Agent, right click on "Jobs" and select "New Job..."

in "Steps", create a "New..." one and enter this:

DELETE YourTable WHERE YourDate<GETDATE()-7

or without regards to time use:

DELETE YourTable WHERE YourDate<DATEADD(day,DATEDIFF(day,0,GETDATE()-7),0)

in "Schedule", you can make it run every Sunday or whatever you need.

like image 137
KM. Avatar answered Sep 18 '22 23:09

KM.


You can create a job that deletes everything older than a week. For example,

DELETE FROM MyTable
WHERE DateCreated <= dateadd(d, -7, getdate())

This assumes, though, that you have some way of tracking how old your records are in the table, and it also assumes there are no foreign key constraints.

You can then schedule the job to run when users aren't connected.

like image 38
LittleBobbyTables - Au Revoir Avatar answered Sep 20 '22 23:09

LittleBobbyTables - Au Revoir