Considering these tables:
CREATE TABLE Status (current_partition INT) -- has a single row
CREATE TABLE RecordedValues (partition INT, value INT)
Let’s say there are multiple clients that frequently insert into the RecordedValues table using the current_partition, e.g.:
DECLARE @current_partition INT
SET @current_partition = (SELECT TOP 1 current_partition FROM Status)
INSERT RecordedValues VALUES (@current_partition, 132)
Concurrently, there is a client which (periodically) modifies the current_partition, then reads all values with the old partition value, e.g.:
DECLARE @old_partition INT
SET @old_partition = (UPDATE Status
SET current_partition += 1
OUTPUT deleted.*)
--
SELECT * FROM RecordedValues WHERE partition = @old_partition
How can I ensure the latter client really selects all the rows with the old partition value? In other words, I need to ensure no INSERTs will be committed after the SELECT returns.
Run your commands in a transaction, and set the isolation level to REPEATABLE READ:
This will ensure consistency between the statements within your transaction.
To quote the docs:
“Specifies that statements cannot read data that has been modified but not yet committed by other transactions and that no other transactions can modify data that has been read by the current transaction until the current transaction completes.”