Handling Blocking in SQL 2005 with LOCK_TIMEOUT and TRY CATCH statements
Handing Blocking and Deadlocks in SQL Stored Procedures
- Ensuring all tables were covered by indexes to speed up any record retrieval
- Reducing the DELETE into small batches of 1000 or 100 at a time in a WHILE loop to reduce the length of time the LOCK was held each time.
- Ensuring any unimportant SELECT statements from these tables were using WITH (NOLOCK) to get round any locking issues.
CREATE PROCEDURE [dbo].[usp_net_update_banner_hit]
@BannerIds varchar(200), -- CSV of banner IDs e.g 100,101,102
@HitType char(1) = 'V', -- V = banner viewed, H = banner hit
AS
SET NOCOUNT ON
SET LOCK_TIMEOUT 500 -- set to half a second
DECLARE @Tries tinyint
SELECT @Tries = 1
-- loop for 3 attempts
WHILE @Tries <= 3
BEGIN
BEGIN TRANSACTION
BEGIN TRY
-- insert our banner hits we are only going to wait half a second
INSERT INTO tbl_BANNER_DATA
(BannerFK, HitType, Stamp)
SELECT [Value], @HitType, getdate()
FROM dbo.udf_SPLIT(@BannerIds,',') -- UDF that splits a CSV into a table variable
WHERE [Value] > 0
--if we are here its been successful ie no deadlock or blocking going on
COMMIT
-- leave our loop
BREAK
END TRY
BEGIN CATCH
--always rollback
ROLLBACK
-- Check for Blocking errors 1222 or Deadlocks 1205 and if its a deadlock wait for a while to see if that helps
IF ERROR_NUMBER() = 1205 OR ERROR_NUMBER() = 1222
BEGIN
-- if its a deadlock wait 2 seconds then try again
IF ERROR_NUMBER() = 1205
BEGIN
-- wait 2 seconds to see if that helps the deadlock
WAITFOR DELAY '00:00:02'
END
-- ELSE
-- no need to wait for anything for BLOCKING ERRORS as our LOCK_TIMEOUT is going to wait for half a second anyway
-- and if it hasnt finished by then (x 3) there is no point waiting any longer
END
--increment and try again
SELECT @Tries = @Tries + 1
-- carry on until we do it 3 times
CONTINUE
END CATCH;
END
Labels: blocking, Deadlocks, LOCK_TIMEOUT, SQL 2005, SQL 2008, Timeouts



0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
Links to this post:
Create a Link
<< Home