I usually use something like this:
update OrderNumberInfo with (rowlock) set @OrderNumber = OrderNumber, OrderNumber = OrderNumber + 1 where VendorID = @VendorID
It should not be wrapped in a transaction. In fact, if you complete the transaction, then SQL Server will start holding locks on the table and slow down everything. When I need to do such things in a web service, I always execute it on a separate database connection outside of any transaction that might be open at that time, just to make sure.
I believe (but have not proven) that SQL Server uses a latch, not a transaction, to make it atomic, which should be more efficient.
If your table design is such that the provider row should be created on demand, if it does not exist, then use this logic:
declare @error int, @rowcount int -- Attempt to read and update the number. update OrderNumberInfo with (rowlock) set @OrderNumber = OrderNumber, OrderNumber = OrderNumber + 1 where VendorID = @VendorID select @error = @@error, @rowcount = @@rowcount if @error <> 0 begin return @error end -- If the update succeeded then exit now. if @rowcount > 0 begin return 0 end -- Insert the row if it doesn't exist yet. insert into OrderNumberInfo (VendorID, OrderNumber) select VendorID, 1 where not exists (select null from OrderNumberInfo where VendorID = @VendorID) select @error = @@error if @error <> 0 begin return @error end -- Attempt to read and update the number. update OrderNumberInfo with (rowlock) set @OrderNumber = OrderNumber, OrderNumber = OrderNumber + 1 where VendorID = @VendorID select @error = @@error if @error <> 0 begin return @error end
This code still does not require a transaction, because each atomic operator will work regardless of how many other connections the code executes at the same time.
Disclaimer: I used this without problems on SQL Server 7-2005. I still can not comment on his behavior in 2008.
Christian hayter
source share