Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use LOCKs to make things SERIALIZABLE but this reduces concurrency. Why not try the common condition first ("mostly insert or mostly select") followed by safe handling of "remedial" action? That is, the "JFDI" pattern...</p> <p>Mostly INSERTs expected (ball park 70-80%+):</p> <p>Just try to insert. If it fails, the row has already been created. No need to worry about concurrency because the TRY/CATCH deals with duplicates for you. </p> <pre><code>BEGIN TRY INSERT Table VALUES (@Value) SELECT @id = SCOPEIDENTITY() END TRY BEGIN CATCH IF ERROR_NUMBER() &lt;&gt; 2627 RAISERROR etc ELSE -- only error was a dupe insert so must already have a row to select SELECT @id = RowID FROM Table WHERE RowValue = @VALUE END CATCH </code></pre> <p>Mostly SELECTs:</p> <p>Similar, but try to get data first. No data = INSERT needed. Again, if 2 concurrent calls try to INSERT because they both found the row missing the TRY/CATCH handles.</p> <pre><code>BEGIN TRY SELECT @id = RowID FROM Table WHERE RowValue = @VALUE IF @@ROWCOUNT = 0 BEGIN INSERT Table VALUES (@Value) SELECT @id = SCOPEIDENTITY() END END TRY BEGIN CATCH IF ERROR_NUMBER() &lt;&gt; 2627 RAISERROR etc ELSE SELECT @id = RowID FROM Table WHERE RowValue = @VALUE END CATCH </code></pre> <p>The 2nd one appear to repeat itself, but it's highly concurrent. Locks would achieve the same but at the expense of concurrency...</p> <p>Edit:</p> <p>Why <strong><em>not</em></strong> to use MERGE...</p> <p>If you use the OUTPUT clause it will only return what is updated. So you need a dummy UPDATE to generate the INSERTED table for the OUTPUT clause. If you have to do dummy updates with many calls (as implied by OP) that is a lot of log writes <em>just</em> to be able to use MERGE. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload