简体   繁体   中英

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?

The documentation says:

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.

I haven't tried this myself though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM