Skip to content

Instantly share code, notes, and snippets.

@ronascentes
Last active February 17, 2022 19:48
Show Gist options
  • Save ronascentes/777f0e2dd0a2c86224d55e05feaf9a4f to your computer and use it in GitHub Desktop.
Save ronascentes/777f0e2dd0a2c86224d55e05feaf9a4f to your computer and use it in GitHub Desktop.
Delete/ Update a large amount of records
-- got from https://sqlperformance.com/2013/03/io-subsystem/chunk-deletes
DECLARE @rows INT, @ErrorMessage NVARCHAR(4000);
SET NOCOUNT, XACT_ABORT ON;
SET @rows = 1;
BEGIN TRY
WHILE (@rows > 0)
BEGIN
BEGIN TRANSACTION;
DELETE TOP (100000) dbo.<table_name> WHERE <clause_statement>;
SET @rows = @@ROWCOUNT;
COMMIT TRANSACTION;
END;
END TRY
BEGIN CATCH
PRINT N'Error while purging <table_name>';
SELECT @ErrorMessage = ERROR_MESSAGE();
PRINT @ErrorMessage;
IF (XACT_STATE()) = -1
ROLLBACK TRANSACTION;
IF (XACT_STATE()) = 1
COMMIT TRANSACTION;
THROW;
END CATCH;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment