views:

50

answers:

1

I want to perform a update then select the result. I don't want anything to be able to update the row I am updating until after the select has occurred. How would I do this?

My goal is to increment a value of a row and return that incremented value. I have thus far found that I end up with an issue where update (to increment) followed by a select in a situation where two queries happen at near the same time the selects seem to return the same number. So I am guessing that something like update > update > select > select is happening.

I miss labeled this as SQL Server 2005. I am actually working with Server 2000. So the output clause does not work (is not in that version).

BEGIN TRANSACTION
UPDATE Table SET Last=(Last+1) WHERE ID=someid;
SELECT * FROM Table WHERE ID=someid;
COMMIT TRANSACTION
+3  A: 
BEGIN TRAN
UPDATE ...
SELECT...
COMMIT 

Should do it even at the default transaction isolation level of read committed.

You could also use the OUTPUT clause to get the row directly back after the update. Example of this

UPDATE <YourTable>
   SET ...
OUTPUT INSERTED.*
 WHERE ...
Martin Smith
Thanks, Begin/Commit is exactly what I was looking for.
aepheus
Just for completeness I should probably mention that if your where clause isn't on something guaranteed to be unique and you want to be sure that your select doesn't return any additional rows inserted after the update that match the where clause you would need to use the SERIALIZABLE isolation level.
Martin Smith
This didn't seem to work as I'd have expected. Testing this morning seems to show that there is still an issue with updating and selecting. It seems like two "update then select" calls can come in and happen something like this: update > update > select > select. Where both selects end up with the same value, when they should have different values. note: this is all on the same row.
aepheus
@aepheus That can't happen like that the first UPDATE will get an exclusive lock on the row and this won't get released until the transaction is committed. Meaning the other transaction will have to wait. There must be something else going on. Maybe update your question with some more details of exactly what you are doing. Also is there any reason why the OUTPUT clause won't work for you? Are you returning additional rows or something?
Martin Smith
As it turns out your solution was correct. It's just that classic asp ADO is not equipped to handle it in that form. Rather I had to set up the transaction using functions of ADO rather than in SQL. I'm guessing a stored proc would have works as well.
aepheus