I have a procedure like this:
create procedure Checkout
@Foo nvarchar(20),
@cost float
as
begin transaction
declare @Bar nvarchar(20);
select @Bar = Bar from oFoo where Foo = @Foo;
update Foo set gold = gold - @cost where name = @Foo;
update Bar set gold = gold + @cost where name = @Bar;
delete from oFoo where @Foo = Foo;
commit transaction
I need to lock the row with Foo = @Foo from oFoo table during this transaction so that nobody could read/edit/delete it, anybody knows how to do that ?
I am using Microsoft SQL Server 2008
If you want nobody to update/delete the row, I would go with the UPDLOCK on the SELECT statement. This is an indication that you will update the same row shortly, e.g.
Now if you want the situation where nobody should be able to read the value as well, I’d use the ROWLOCK (+HOLDLOCK XLOCK to make it exclusive and to hold until the end of the transaction).
You can do TABLOCK(X), but this will lock the whole table for exclusive access by that one transaction. Even if somebody comes along and wants to execute your procedure on a different row (e.g. with another @Foo value) they will be locked out until the previous transaction completed.
Note: you can simulate different scenarios with this script:
client #1
client #2: