I have an application that needs to make an atomic update to an item in a table. It has to read the value, do something complicated to it, and write it back, and in the meantime no one else should be able to overwrite the value. So what I'm doing is like this:
SELECT state FROM tab WHERE id=7
Then the program does something complex based on value of state. Then:
UPDATE tab SET state=some_new_value WHERE id=7
Problem is, between the SELECT and UPDATE, some other user can come in an overwrite state, because the table hasn't been locked at that point.
My solution was to make a trivial update to the table first, like this:
UPDATE table SET id=7 WHERE id=7
This locks the table from overwriting by other users. Then I can proceed with the SELECT, and COMMIT the transaction after the UPDATE. This does what I want to, mostly, but it feels icky, and I am afraid it make my code prone to unpleasant corner cases if another user deletes the row.
This app is otherwise vanilla SQL with simple data requirements. I don't know much about SQL Server in particular.
Thanks for any suggestions.