Skip to content

Commit 532021d

Browse files
authored
+ Added a batch-deletion script for purging ExceptionLog records older than a specified date. Useful for safely managing large cleanup operations without long-running transactions.
1 parent f48488e commit 532021d

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
-- =====================================================================================================
2+
-- Author: Nick Airdo
3+
-- Create Date: 3/1/2025
4+
-- Description: Deletes ExceptionLog records older than a specified date in batches.
5+
-- Notes: Useful for cleaning up old exceptions in a controlled way. The loop deletes in batches
6+
-- of 5,000 rows to avoid long-running transactions and excessive locking.
7+
-- Set @DeleteOlderThanDate to your desired cutoff.
8+
-- Set @MAX_TIMES_TO_LOOP to limit the number of iterations (for safety or testing).
9+
--
10+
-- You can optionally use TRANSACTION statements to test this script without committing changes.
11+
-- Use with caution in production environments.
12+
--
13+
-- PRINT Statement Behavior:
14+
-- SQL Server buffers PRINT statements and sends them to the client only when a batch completes
15+
-- or the buffer fills. Azure Data Studio may delay these messages more than SSMS due to differences
16+
-- in how each handles output buffering.
17+
--
18+
-- Change History:
19+
--
20+
-- =====================================================================================================
21+
22+
DECLARE @MAX_TIMES_TO_LOOP INT = 100 -- set to lower if you just want to test.
23+
DECLARE @DeleteOlderThanDate DATETIME = '10/1/2025'
24+
25+
--BEGIN TRANSACTION -- uncomment if you want to only test (and the ROLLBACK below)
26+
27+
-------------------------------------------------------------------------------------------------------
28+
29+
DECLARE @Rows INT
30+
SET @Rows = 1
31+
DECLARE @Counter INT
32+
SET @Counter = 0
33+
34+
SELECT COUNT(*) FROM ExceptionLog WHERE CreatedDateTime < @DeleteOlderThanDate
35+
36+
WHILE (@Rows > 0 AND @Counter < @MAX_TIMES_TO_LOOP)
37+
BEGIN
38+
DELETE TOP (5000) FROM ExceptionLog
39+
WHERE CreatedDateTime < @DeleteOlderThanDate
40+
SET @Rows = @@ROWCOUNT
41+
SET @Counter = @Counter + 1
42+
-- Display the current loop iteration
43+
SELECT 'Loop #' AS Message, @Counter AS CurrentLoop, @Rows AS RowsDeleted
44+
PRINT 'Loop #: ' + CONVERT(VARCHAR, @Counter);
45+
46+
-- This command forces all previous PRINT statements to be sent to the client immediately
47+
RAISERROR(N'', 0, 1) WITH NOWAIT;
48+
49+
END
50+
51+
SELECT COUNT(*) FROM ExceptionLog WHERE CreatedDateTime < @DeleteOlderThanDate
52+
--ROLLBACK TRANSACTION -- uncomment if you want to only test

0 commit comments

Comments
 (0)