I've created a maintenance stored procedure to delete data older than 30 days on events table.
What are the best practices for deleting data?
I've encased the procedure with
error handling, i.e. TRY... CATCH
,
and also used SET XACT_ABORT ON
- for timeout error from application.
Should I use a loop in running the delete process, as to not fill the transaction log?
Right now I don't expect many rows to be deleted but what happens if there are millions of rows?
Here is the code I've written:
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION
DELETE FROM Saga.SagaEvents
WHERE Created < DATEADD(DAY,-@NumDays,GETUTCDATE())
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
END
GO
SELECT ERROR_MESSAGE
etc just doTHROW;
. How is the error-handling tag relevant?