In order to retrieve an ID, I first do a select and then an update, in two consequent queries.
The problem is that I am having problems with locked rows. I've read that putting both this statements, Select and Update in one stored procedure it helps with the locks. Is this true?
The queries I run are:
select counter
from dba.counter_list
where table_name = :TableName
update dba.counter_list
set counter = :NewCounter
where table_name = :TableName
The problem is that it can happen that multiple users are selecting the same row and also possible that they update the same row.
Assumptions:
select
returns a single value for counter
counter
value for some purpose other than performing the updateConsider the following update
statement which should eliminate any race conditions that may occur with multiple users running your select/update
logic concurrently:
declare @counter int -- change to the appropriate datatype
update dba.counter_list
set @counter = counter, -- grab current value
counter = :NewCounter -- set to new value
where table_name = :TableName
select @counter -- send previous counter value to client
update
obtains an exclusive lock on the desired row (or page/table depending on table design and locking scheme)Whether you submit the above via a SQL batch or a stored proc call is up to you and your DBA to decide ...