Which lock hints should I use (T

I want to implement an atomic transaction like the following:

BEGIN TRAN A

SELECT id
FROM Inventory
WITH (???)
WHERE material_id = 25 AND quantity > 10

/*
Process some things using the inventory record and
eventually write some updates that are dependent on the fact that
that specific inventory record had sufficient quantity (greater than 10).
*/

COMMIT TRAN A

The problem is that there are other transactions happening that consume quantity from our inventory, so between the time that the record is selected and the updates are written in transaction A that record could become an invalid selection because it's quantity might have been lowered below the threshold in the WHERE clause.

So the question is what locking hints should I use in the WITH clause to prevent the selected inventory record from being changed before I finish my updates and commit the transaction?

EDIT: So thanks to John, a good solution seems to be to set the transaction isolation level to REPEATABLE READ. This will will make sure that "no other transactions can modify data that has been read by the current transaction until the current transaction completes."


You may actually be better off setting the transaction isolation level rather than using a query hint.

The following reference from Books Online provides details of each of the different Isolation levels.

http://msdn.microsoft.com/en-us/library/ms173763.aspx

Here is good article that explains the various types of locking behaviour in SQL Server and provides examples too.

http://www.sqlteam.com/article/introduction-to-locking-in-sql-server


table hints

WITH (HOLDLOCK) allows other readers. UPDLOCK as suggested elsewhere is exclusive.

HOLDLOCK will prevent other updates but they may use the data that is updated later.

UPDLOCK will prevent anyone reading the data until you commit or rollback.

Have you looked at sp_getapplock? This would allow you to serialise this code (if it's the only update bit) without UPDLOCK blocking

Edit: The problem lies mainly in this code running in 2 different sessions. With HOLDLOCk or REPEATABLE_READ, the data will be read in the 2nd session before the 1st session update. With UPDLOCK, noone can read the data in any session.


MSSQL:

SELECT id
FROM Inventory (UPDLOCK)
WHERE material_id = 25 AND quantity > 10;

http://www.devx.com/tips/Tip/13134



By any chance you're interested with PostgreSQL:

SELECT id
FROM Inventory    
WHERE material_id = 25 AND quantity > 10
FOR UPDATE;
链接地址: http://www.djcxy.com/p/32826.html

上一篇: varchar和nvarchar有什么区别?

下一篇: 我应该使用哪些锁定提示(T