[英]Sql Server: Lock all records returned by select statement
I have a situation where I need to select some records from a table, store the primary keys of these records in a temporary table, and apply an exclusive lock to the records in order to ensure that no other sessions process these records. 我遇到一种情况,我需要从表中选择一些记录,将这些记录的主键存储在临时表中,并对这些记录应用排他锁,以确保没有其他会话处理这些记录。 I accomplish this with locking hints:
我通过锁定提示来完成此操作:
begin tran
insert into #temp
select pk from myTable with(xlock)
inner join otherTables, etc
(Do something with records in #temp, after which they won't be candidates for selection any more)
commit
The problem is that many more records are being locked than necessary. 问题在于,更多的记录被锁定,超出了必要。 I'd like to only lock the records that are actually inserted into the temporary table.
我只想锁定实际插入到临时表中的记录。 I was initially setting a flag on the table to indicate the record was in use (as opposed to using lock hints), but this had problems because the database would be left in an invalid state if a situation prevented one or more records being processed.
我最初是在表上设置一个标志以指示该记录正在使用中(而不是使用锁定提示),但这存在问题,因为如果情况阻止处理一个或多个记录,数据库将处于无效状态。
Maybe setting a different isolation level and using the rowlock table hint is what you're looking for? 也许正在设置其他隔离级别并使用行锁表提示是您要寻找的东西?
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
and 和
WITH (ROWLOCK)
Or maybe combining XLOCK and ROWLOCK might do the trick? 也许结合使用XLOCK和ROWLOCK可能会成功?
The documentation says: 该文件说:
XLOCK
XLOCK
Specifies that exclusive locks are to be taken and held until the transaction >completes.
指定要获取并持有排他锁,直到事务>完成。 If specified with ROWLOCK, PAGLOCK, or TABLOCK, the exclusive locks apply to >the appropriate level of granularity.
如果用ROWLOCK,PAGLOCK或TABLOCK指定,则排他锁适用于适当的粒度级别。
I haven't tried this myself though. 我自己还没有尝试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.