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

与世无争的帅哥 提交于 2019-11-30 18:59:16

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!