Safe solutions for INSERT OR UPDATE on SQL Server 2016
<p>Assume a table structure of MyTable(MyTableId NVARCHAR(MAX) PRIMARY KEY, NumberOfInserts INTEGER).</p>

<p>I often need to either update i.e. increment a counter of an existing record, or insert a new record if it doesn't exist with a value of 0 for NumberOfInserts.</p>

<p>Essentially:</p>

<pre><code>IF (MyTableId exists)
    run UPDATE command
ELSE
    run INSERT command
</code></pre>

<p>My concern is losing data due to race conditions, etc.</p>

<p>What's the <strong>safest</strong> way to write this?</p>

<p>I need it to be 100% accurate if possible, and willing to sacrifice speed where necessary.</p>