title: In SQL Server, how can I lock a single row in a way similar to Oracle's "SELECT FOR UPDATE WAIT"?
body: <p>I have a program that connects to an Oracle database and performs operations on it. I now want to adapt that program to also support an SQL Server database.</p>
  
  <p>In the Oracle version, I use "SELECT FOR UPDATE WAIT" to lock specific rows I need.  I use it in situations where the update is based on the result of the SELECT and other sessions can absolutely not modify it simultaneously, so they must manually lock it first.  The system is highly subject to sessions trying to access the same data at the same time.</p>
  
  <p>For example:<br>
  Two users try to fetch the row in the database with the highest priority, mark it as busy, performs operations on it, and mark it as available again for later use.
  In Oracle, the logic would go basically like this:</p>
  
  <pre><code>BEGIN TRANSACTION;
  SELECT ITEM_ID FROM TABLE_ITEM WHERE ITEM_PRIORITY &gt; 10 AND ITEM_CATEGORY = 'CT1'
      ITEM_STATUS = 'available' AND ROWNUM = 1 FOR UPDATE WAIT 5;
  UPDATE [locked item_id] SET ITEM_STATUS = 'unavailable';
  COMMIT TRANSACTION;
  </code></pre>
  
  <p>Note that the queries are built dynamically in my code.  Also note that when the previously most favorable row is marked as unavailable, the second user will automatically go for the next one and so on.  Furthermore, different users working on different categories will not have to wait for each other's locks to be released.  Worst comes to worst, after 5 seconds, an error would be returned and the operation would be cancelled.</p>
  
  <p>So finally, the question is: how do I achieve the same results in SQL Server?  I have been looking at locking hints which, in theory, seem like they should work.  However, the only locks that prevents other locks are "UPDLOCK" AND "XLOCK" which both only work at a table level.<br>
  Those locking hints that do work at a row level are all shared locks, which also do not satisfy my needs (both users could lock the same row at the same time, both mark it as unavailable and perform redundant operations on the corresponding item).</p>
  
  <p>Some people seem to add a "time modified" column so sessions can verify that they are the ones who modified it, but this sounds like there would be a lot of redundant and unnecessary accesses.</p>