title: T-SQL Insert or update
body: <p>I have a question regarding performance of SQL Server.</p>
  
  <p>Suppose I have a table <code>persons</code> with the following columns: <code>id</code>, <code>name</code>, <code>surname</code>.</p>
  
  <p>Now, I want to insert a new row in this table. The rule is the following:</p>
  
  <ol>
  <li><p>If <code>id</code> is not present in the table, then insert the row.</p></li>
  <li><p>If <code>id</code> is present, then update.</p></li>
  </ol>
  
  <p>I have two solutions here:</p>
  
  <p>First:</p>
  
  <pre><code>update persons
    set id=@p_id, name=@p_name, surname=@p_surname
  where id=@p_id
  if @@ROWCOUNT = 0 
    insert into persons(id, name, surname)
    values (@p_id, @p_name, @p_surname)
  </code></pre>
  
  <p>Second:</p>
  
  <pre><code>if exists (select id from persons where id = @p_id)
    update persons
      set id=@p_id, name=@p_name, surname=@p_surname
    where id=@p_id
  else
    insert into persons(id, name, surname)
    values (@p_id, @p_name, @p_surname)
  </code></pre>
  
  <p>What is a better approach? It seems like in the second choice, to update a row, it has to be searched two times, whereas in the first option - just once. Are there any other solutions to the problem? I am using MS SQL 2000.</p>