On a MS SQL server, you have a handy data type, timestamp
, that allows you to do this quite easily. The update will then look like this:
update [table] set ... where [Id] = @Id and [Version] = @Version;
(the version will be automatically updated if the update comes through, so you don't need to change it manually)
So, if someone modified the row in the meantime, this will modify zero rows (you can check this easily), and if not, you'll push your changes and the version number has a new value automatically.
Even if you don't have something like the timestamp
data type, the approach still works as long as you make the change in a single update (or, depending on the transaction model, a single transaction). The key here is the where
clause, which forbids you to change anything if the version in DB isn't the one you loaded before you started your changes. Using this, you can simply do
update [table] set ..., [Version] = @Version + 1
where [Id] = @Id and [Version] = @Version;
This effectively works the same way as with the timestamp
data type - if someone increased the version in the meantime, your update isn't going to update anything.