July 1, 2024 at 11:31 pm
I have a table with data appending on a daily basis. We plan to keep the set of data in this table for one full year and delete everything after August 1st of every year.
I am stuck with the query logic to do this. The situations are like this:
If today's date is August 1st, regardless of the year, delete data from the entire table. Or else, do nothing and keep appending the data. The getdate() can be used as well but needs to round down the time to midnight of August the 1st.
Any suggestions? Thanks.
July 2, 2024 at 3:48 pm
Assuming you delete/append once per day, can you truncate the table if today is the 1st of August? This is set to truncate on the 2nd of July for testing. If the code will run multiple times per day then I would change it to delete where DateTimeColumn < TargetDate.
DROP TABLE IF EXISTS dbo.AppendData
CREATE TABLE dbo.AppendData (Col1 INT, Col2 INT, DateTimeColumn DATETIME)
GO
DECLARE @Today DATE,
@TargetDate DATE
SET @Today = CAST(GETDATE() AS DATE)
SET @TargetDate = DATEFROMPARTS(DATEPART(YEAR,GETDATE()),7,2)
IF @Today = @TargetDate
BEGIN
TRUNCATE TABLE dbo.AppendData
--OR
DELETE dbo.AppendData
WHERE DateTimeColumn < CAST(@TargetDate AS DATETIME)
END
GO
DROP TABLE IF EXISTS dbo.AppendData
July 2, 2024 at 6:52 pm
I wouldn't use DELETE on a year old table. That'll be a lot to delete and it'll cause a "log file explosion".
I probably also wouldn't do a whole year at a time but that might just be me.
--Jeff Moden
Change is inevitable... Change for the better is not.
July 2, 2024 at 7:16 pm
If you are dealing with large amounts of transactional data you may also want to look at table partitioning or partitioned views.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply