title: SQL Server : add row if doesn't exist, increment value of one column, atomic
body: <p>I have a table that keeps a count of user actions. Each time an action is done, the value needs to increase. Since the user can have multiple sessions at the same time, the process needs to be atomic to avoid multi-user issues.</p>
  
  <p>The table has 3 columns:</p>
  
  <ul>
  <li><code>ActionCode</code> as <code>varchar</code></li>
  <li><code>UserID</code> as <code>int</code></li>
  <li><code>Count</code> as <code>int</code></li>
  </ul>
  
  <p>I want to pass <code>ActionCode</code> and <code>UserID</code> to a function that will add a new row if one doesn't already exist, and set count to 1. If the row does exist, it will just increase the count by one.  <code>ActionCode</code> and <code>UserID</code> make up the primary unique index for this table.</p>
  
  <p>If all I needed to do was update, I could do something simple like this (because an <code>UPDATE</code> query is atomic already):</p>
  
  <pre><code>UPDATE (Table)
  SET Count = Count + 1 
  WHERE ActionCode = @ActionCode AND UserID = @UserID
  </code></pre>
  
  <p>I'm new to atomic transactions in SQL. This question has probably been answered in multiple parts here, but I'm having trouble finding those and also placing those parts in one solution. This needs to be pretty fast as well, without getting to complex, because these actions may occur frequently.</p>
  
  <p>Edit: Sorry, this might be a dupe of <a href="https://stackoverflow.com/questions/4728325/mysql-how-to-do-an-if-exist-increment-in-a-single-query">MySQL how to do an if exist increment in a single query</a>. I searched a lot but had <code>tsql</code> in my search, once I changed to <code>sql</code> instead, that was the top result. It isn't obvious if that is atomic, but pretty sure it would be. I'll probably vote to delete this as dupe, unless someone thinks there can be some new value added by this question and answer.</p>