Skip to content

Instantly share code, notes, and snippets.

@Codesleuth
Last active January 26, 2016 13:09
Show Gist options
  • Save Codesleuth/2fc4526e3b2eaf00c97c to your computer and use it in GitHub Desktop.
Save Codesleuth/2fc4526e3b2eaf00c97c to your computer and use it in GitHub Desktop.
Retryable SQL

Retryable SQL Script

Allows retrying a SQL script until a lock can be achieved necessary to do the work.

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