How to explicitly lock a table in Microsoft SQL Server (looking for a hack - uncooperative client)

后端 未结 3 836
礼貌的吻别
礼貌的吻别 2021-01-05 00:38

This was my original question:

I am trying to figure out how to enforce EXCLUSIVE table locks in SQL Server. I need to work around uncooperative readers (beyond m

相关标签:
3条回答
  • 2021-01-05 00:42

    Add a locking hint to your SELECT:

    SELECT COUNT(*) FROM artist WITH (TABLOCKX)

    and put your INSERT into a transaction.

    If your initial statement is in an explicit transaction, the SELECT will wait for a lock before it processes.

    0 讨论(0)
  • 2021-01-05 00:52

    There's no direct way to force locking when a connection is in the READ UNCOMMITTED isolation level.

    A solution would be to create views over the tables being read that supply the READCOMMITTED table hint. If you control the table names used by the reader, this could be pretty straightforward. Otherwise, you'll have quite a chore as you'll have to either modify writers to write to new tables or create INSTEAD OF INSERT/UPDATE triggers on the views.

    Edit:

    Michael Fredrickson is correct in pointing out that a view simply defined as a select from a base table with a table hint wouldn't require any trigger definitions to be updatable. If you were to rename the existing problematic tables and replace them with views, the third-party client ought to be none the wiser.

    0 讨论(0)
  • 2021-01-05 01:01

    One hack hack hack way to do this is to force an operation on the table which takes a SCH-M lock on the table, which will prevent reads against the table even in READ UNCOMMITTED isolation level. Eg, doing an operation like ALTER TABLE REBUILD (perhaps on a specific empty partition to reduce performance impact) as part of your operation will prevent all concurrent access to the table until you commit.

    0 讨论(0)
提交回复
热议问题