The following code is designed to loop through and delete transactions by the month. However, it did not perform in the manner that I expected. I was expecting the COMMIT to occur after each DELETE.
The routine failed when it ran out of log space and rolled back ALL of the transactions that it deleted. The COMMIT
did not perform in the manner that I was expecting. In an effort to control the log space I assumed the COMMIT
within the loop would COMMIT
each monthly delete and therefore, prevent the log space from over filling.
DECLARE @MaxPostDate AS DATE = '2021-01-31'
DECLARE @MinPostDate AS DATE = '2019-07-01'
DECLARE @NbrOfMonthsToMaintain As INT = 13
WHILE @NbrOfMonthsToBeDeleted >= 0
BEGIN
SELECT @NbrOfTransactions = COUNT(*)
FROM [dbo].[Transaction] f
WHERE f.[PostDate] BETWEEN @StartingDeleteDate AND EOMONTH(@StartingDeleteDate)
PRINT 'Delete ' + FORMAT(@NbrOfTransactions,'N0') + ' transactions between '
+ CAST(@StartingDeleteDate As VARCHAR(20)) + ' AND '
+ CAST(EOMONTH(@StartingDeleteDate) AS VARCHAR(20))
BEGIN TRANSACTION
DELETE f
FROM [dbo].[Transaction] f
WHERE f.[PostDate] BETWEEN @StartingDeleteDate AND EOMONTH(@StartingDeleteDate)
AND f.[PostDate] <= @DeleteToDate
COMMIT TRANSACTION
INSERT INTO [app].[DataDeletionHistory](
[DataType]
,[Description]
,[DateDeleted]
,[MonthDeleted]
,[RowsDeleted])
SELECT 'Transactions' As DataType
,'Delete' As [Description]
,GetDate() AS DateDeleted
,@StartingDeleteDate AS MonthDeleted
,@NbrOfTransactions AS RowsDeleted
SET @StartingDeleteDate = DATEADD(m,1,@StartingDeleteDate)
SET @NbrOfMonthsToBeDeleted = @NbrOfMonthsToBeDeleted - 1
END;
Following are the results:
Delete 15,183,513 transactions between 2019-07-01 AND 2019-07-31
(15183513 rows affected)
(1 row affected)
Delete 14,999,308 transactions between 2019-08-01 AND 2019-08-31
(14999308 rows affected)
(1 row affected)
Delete 14,292,165 transactions between 2019-09-01 AND 2019-09-30
(14292165 rows affected)
(1 row affected)
Delete 15,365,025 transactions between 2019-10-01 AND 2019-10-31
(15365025 rows affected)
(1 row affected)
Delete 14,576,586 transactions between 2019-11-01 AND 2019-11-30
(14576586 rows affected)
(1 row affected)
Delete 15,316,013 transactions between 2019-12-01 AND 2019-12-31
(15316013 rows affected)
(1 row affected)
Delete 15,453,046 transactions between 2020-01-01 AND 2020-01-31
(15453046 rows affected)
(1 row affected)
Delete 14,408,066 transactions between 2020-02-01 AND 2020-02-29
Msg 9002, Level 17, State 4, Line 50
The transaction log for database 'MyDatabase' is full due to 'ACTIVE_TRANSACTION'.Msg 9002, Level 17, State 4, Line 1
The transaction log for database 'MyDatabase' is full due to 'ACTIVE_TRANSACTION'.Msg 3314, Level 21, State 3, Line 1