Allows retrying a SQL script until a lock can be achieved necessary to do the work.
Last active
January 26, 2016 13:09
-
-
Save Codesleuth/2fc4526e3b2eaf00c97c to your computer and use it in GitHub Desktop.
Retryable SQL
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
USE [YourDatabase]; | |
SET LOCK_TIMEOUT 1000; | |
DECLARE @msg nvarchar(100) | |
DECLARE @attempts int | |
DECLARE @completed bit | |
SELECT @completed = 0, @attempts = 0 | |
WHILE (@completed = 0) | |
BEGIN | |
BEGIN TRY | |
SET @attempts = @attempts + 1 | |
SET @msg = '[' + CONVERT(nvarchar, @attempts) + '] Trying ...' | |
RAISERROR (@msg, 10, 1) WITH NOWAIT | |
BEGIN TRAN | |
-- Put your retrying code here... | |
-- For example... | |
ALTER TABLE [YourTable] | |
ALTER COLUMN [Whatever] NVARCHAR(254) | |
SET @completed = 1 | |
COMMIT TRAN | |
SET @msg = '[' + CONVERT(nvarchar, @attempts) + '] Done.' | |
RAISERROR (@msg, 10, 1) WITH NOWAIT | |
END TRY | |
BEGIN CATCH | |
ROLLBACK TRAN | |
SET @msg = '[' + CONVERT(nvarchar, @attempts) + '] Failed: ' + ERROR_MESSAGE() | |
RAISERROR (@msg, 10, 1) WITH NOWAIT | |
END CATCH | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment