Detect a competing update with rowversion
Use a rowversion token in an update predicate so an application can detect that another writer changed the row.
What you are trying to do
A service reads a job and remembers its token. A simulated competing edit changes the row before the service submits its stale update.
Work through it
- Read the rowversion value as an opaque token. It is not a date or clock time.
- Save the initial token in a local variable.
- Treat the first UPDATE as the competing writer. It changes the token automatically.
- Trace the application UPDATE with the stale token. Its predicate matches no row, so the change is rejected without overwriting the competing edit.
- Only the local temporary table is updated.
Check your work
The stale-token UPDATE reports RowsChanged = 0. The final row remains Status = Claimed, which is the competing writer's value. The rowversion bytes can vary, so verify the match count and status rather than comparing a literal token.
Practice SQL
Open in SQL FlowCREATE TABLE #Job (JobId int NOT NULL PRIMARY KEY, Status nvarchar(20) NOT NULL, VersionToken rowversion);
INSERT INTO #Job (JobId, Status) VALUES (1, N'Queued');
DECLARE @ReadVersion binary(8);
SELECT @ReadVersion = VersionToken FROM #Job WHERE JobId = 1;
UPDATE #Job SET Status = N'Claimed' WHERE JobId = 1;
UPDATE #Job SET Status = N'Completed' WHERE JobId = 1 AND VersionToken = @ReadVersion;
SELECT @@ROWCOUNT AS RowsChanged;
SELECT JobId, Status FROM #Job;
DROP TABLE #Job;
Knowledge check
Commands in this lesson
Next lesson Filter a date range with a half-open boundary