简体   繁体   English

SQL Server:锁定由select语句返回的所有记录

[英]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.

相关问题 选择语句的排他锁和共享锁 - SQL Server - exclusive lock and shared lock for select statement - SQL Server SQL Server - 选择所有顶部的小时记录 - SQL Server - Select all top of the hour records 在SQL Server中的事务中为SELECT语句放置了什么类型的锁 - What kind of lock is placed for SELECT statement within a transaction in SQL Server SQL Server:在一个选择语句中选择多个记录 - SQL Server: Select multiple records in one select statement SQL Server - 按为所有组返回的记录数聚合 - SQL Server - Aggregate by number of records returned for all groups SQL:从SELECT语句返回的所有条目中删除部分字符串 - SQL: Remove part of the string from all the entries returned by the SELECT statement 选择“所有记录”或SQL Server中的最高动态记录数 - Select All records or top dynamic number of records in SQL Server 是否可以使用“WHERE”子句来选择 SQL 语句中的所有记录? - Is it possible to use “WHERE” clause to select all records in SQL Statement? 如何在SQL Server的while循环中使用select语句检索记录? - How to retrieve records using select statement in while loop in SQL Server? SQL Server中根据xml记录中的属性选择语句为varchar - Select statement based on attributes in xml records as varchar in SQL Server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM