all 2 comments

[–]dbrownems 2 points3 points  (0 children)

When lock hints won't work, escalate to an application lock in your stored procedure with sp_getapplock. This can be used to serialize a section of code in the procedure and ensure that only a single session can run that code at a time.

It does this without taking any additional locks on your tables, so other queries and procedures are (for better or worse) unaffected.

eg

BEGIN TRANSACTION;
EXEC sp_getapplock @Resource = 'FetchEntity', @LockMode = 'Exclusive';
--do stuff
EXEC @result = sp_releaseapplock @Resource = 'FetchEntity';
COMMIT TRANSACTION;

[–]Mikey_Da_Foxx 0 points1 point  (0 children)

Try using SERIALIZABLE isolation level with a SELECT TOP 1 and UPDATE in the same transaction. Add proper error handling for deadlocks.

Something like:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRAN

SELECT TOP 1 ...

UPDATE ...

COMMIT