title: Making a TSQL Insert/Update work even when multithreaded
body: <p>I have a table that I use to keep track of customer usage.  I track the number of hits the user does per day, so I have a table that looks like this:</p>
  
  <pre><code>CustID (uniqueidentifier, not null)
  
  UseDate (smalldatetime, not null)
  
  NumHits (smallint, not null)
  </code></pre>
  
  <p>I use this SQL in a stored proc to insert a row for today (if needed), or to increment the counter for today:</p>
  
  <pre><code>declare @today datetime
  set @today = getdate()
  
  /* Try to bump it by one if an entry for today exists */
  if (
      select count(*) from CustomerUsage
      where CustID = @cust_guid and year(UseDate) = year(@today) and month(UseDate) = month(@today) and day(UseDate) = day(@today)
      ) = 0
  
      insert into CustomerUsage (CustID, UseDate, NumHits) values (@cust_guid, getdate(), 1)
  
  else
      update CustomerUsage set NumHits = NumHits + 1 
      where CustID = @cust_guid and year(UseDate) = year(@today) and month(UseDate) = month(@today) and day(UseDate) = day(@today)
  </code></pre>
  
  <p>Is there a better way to do this?</p>
  
  <p>Also, I want to move to an environment where multiple web servers can call the stored proc for the same customer.  I think this code might be vulnerable to multithreading issues.</p>
  
  <p>Thanks!</p>