0

Can anyone please tell me why does the following statement inside a given stored procedure returns repeated results even with locks on the rows used by the first SELECT statement?

BEGIN TRANSACTION DECLARE @Temp TABLE ( ID INT ) INSERT INTO @Temp SELECT ID FROM SomeTable WITH (ROWLOCK, UPDLOCK, READPAST) WHERE SomeValue <= 10 INSERT INTO @Temp SELECT ID FROM SomeTable WITH (ROWLOCK, UPDLOCK, READPAST) WHERE SomeValue >= 5 SELECT * FROM @Temp COMMIT TRANSACTION 

Any values in SomeTable for which SomeValue is between 5 and 10 will be returned twice, even though they were locked in the first SELECT. I thought that locks were in place for the whole transaction, and so I wasn't expecting the query to return repeated results. Why is this happening?

1 Answer 1

1

In the same session/transaction, READPAST won't have any effect.

So even though you have ROWLOCK and UPDLOCK for the first SELECT , the next SELECT ignores these. If the 2nd SELECT was a different session, then it'd work as expected.

See these for more info: ORDER BY and WITH(ROWLOCK, UPDLOCK, READPAST) and TABLOCKX versus SERIALIZABLE

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.