Last active
February 17, 2022 19:48
-
-
Save ronascentes/777f0e2dd0a2c86224d55e05feaf9a4f to your computer and use it in GitHub Desktop.
Delete/ Update a large amount of records
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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