title: SQL Prevent multiple inserts at the same time for non-duplicates
body: <p>I am trying to prevent multiple inserts at the exact same time so I can prevent duplicate inserts. I have two tables:</p>
  
  <ol>
  <li><p>Table B, this table has 4 columns <code>id</code>, <code>timeToken</code>, <code>tokenOrder</code> and <code>taken</code>. </p></li>
  <li><p>Table A which I will be inserting into and that has <code>id</code>, <code>createDate</code> and <code>timeToken</code>. </p></li>
  </ol>
  
  <p>What I am trying to do is prevent the <code>timeToken</code> in Table A not to have duplicate values in the case where multiple inserts are happening at the exact same time. I have the following code:</p>
  
  <pre><code>DECLARE @ReturnValue nvarchar
  
  SELECT Top 1 @ReturnValue=timeToken FROM TableB WHERE taken = 0 Order By tokenOrder
  
  Update TableB SET taken = 1 WHERE timeToken = @ReturnValue
  
  INSERT INTO TableA Values(@ReturnValue, GETDATE())
  </code></pre>
  
  <p>Now that I think about it, is it possible to have my timeToken table in TableA auto increment with the timeToken from TableB?</p>
  
  <p><strong>Table B sample data:</strong></p>
  
  <pre><code>id  timeToken   tokenOrder taken
  1   1:00am      1          0
  2   2:00am      2          0
  3   3:00am      3          1
  4   4:00am      4          0
  5   5:00am      5          0
  </code></pre>
  
  <p>This is what I am expecting Table A to look like after 4 calls all at the exact same time that would cause duplicates (id starting at 5 - this could be because I have deleted old records).</p>
  
  <p><strong>Table A sample data</strong>:</p>
  
  <pre><code>id     createDate                 timeToken
  5      2014-11-22 12:45:34.243    1:00am
  6      2014-11-22 12:45:34.243    2:00am
  7      2014-11-22 12:45:34.243    4:00am
  8      2014-11-22 12:45:34.243    5:00am
  </code></pre>