1

In SQL Server, how can a table be locked and unlocked (exclusively) outside of a transaction?

Reason: multiple instances of my app need to interact with one table without stepping on each other's toes, while at the same time executing a statement that cannot run within a transaction

5
  • In what context. Far too vague Nov 26, 2017 at 15:11
  • 3
    Locks are generally held only for the duration of a transaction. Perhaps what you want is a session level application lock.
    – Dan Guzman
    Nov 26, 2017 at 15:19
  • Application lock could possibly do the job. I'll happily accept an answer that solves it that way. Nov 26, 2017 at 15:22
  • Looks like you needs to keep access blocked for one table except when your app is interacting with it. Maybe you can look in users permissions, Example give permission to only your app to use insert in a table and let other users to only select it by using a view.
    – jean
    Nov 26, 2017 at 18:44
  • No I need multiple instances of my app to interact with one table without stepping on each other's toes, while at the same time executing a statement that cannot run within a transaction. Nov 26, 2017 at 21:56

1 Answer 1

3

One option might be to look into sp_getapplock and sp_releaseapplock.

This would not lock the table, but an arbitrary named resource. You could then configure your application to only work with the table in question after the lock has been acquired, e.g., through stored procedures.

An example of this would be something like:

EXEC sp_getapplock @Resource = 'ResourceName', @LockMode = 'Exclusive', @LockOwner = 'Session'

-- UPDATE table, etc.

EXEC sp_releaseapplock @Resource = 'ResourceName', @LockOwner = 'Session'

Specifying @LockOwner = 'Session' means you can use this locking mechanism outside of a transaction.

There's also the option of extracting the locking and releasing statements into their own stored procedures, so the logic is only stated once; these stored procedures could return a value to the calling procedure with a result specifying whether or not the lock has been acquired/released.

At that point it's just a question of ensuring that this mechanism is put into place for every procedure/table/etc. where there may be contention.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.