Delete rows with date older than 30 days with SQL Server query
Solution 1:
Use DATEADD in your WHERE clause:
...
WHERE date < DATEADD(day, -30, GETDATE())
You can also use abbreviation d
or dd
instead of day
.
Solution 2:
You could also use
SELECT * from Results WHERE date < NOW() - INTERVAL 30 DAY;
Solution 3:
Although the DATEADD
is probably the most transparrent way of doing this, it is worth noting
that simply getdate()-30
will also suffice.
Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:
SELECT *
FROM Results
WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)
Solution 4:
To delete records from a table that have a datetime value in Date_column older than 30 days use this query:
USE Database_name;
DELETE FROM Table_name
WHERE Date_column < GETDATE() - 30
...or this:
USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(dd,-30,GETDATE())
To delete records from a table that have a datetime value in Date_column older than 12 hours:
USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(hh,-12,GETDATE())
To delete records from a table that have a datetime value in Date_column older than 15 minutes:
USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(mi,-15,GETDATE())
From: http://zarez.net/?p=542