title: TSQL: INSERT or UPDATE from SELECT result
body: <p>I have the following query where I grab some data from tables, and use the result to insert into a table called finalTable. finalTable.col1 is a pk. However, there are some rows in the finalTable that already exists with the same pk prior to running the below query. I want to change it so that it inserts(if the pk does not exist in finalTable) or updates(if the pk already exist in finalTable).</p>
  
  <pre><code>INSERT INTO finalTable (col1, col2, col3, col4, col5) 
  (
  SELECT o.id, 14, 0, 1, 4
  FROM Table1 c
  INNER JOIN Table2 m ON c.ID = m.ID 
  INNER JOIN Table3 o ON m.ID = o.ID 
  WHERE c.ID = 40
  )
  </code></pre>
  
  <p>One solution I came up with is deleting any relevant rows in finalTable prior to running the above query.</p>
  
  <p>Another solution I came up with is to use "if exists". I would put the select query in the if exists statement, the clause of the if, and the clause of the else. I don't like this solution as I have to put the select query in 3 places, rather than in just 1 place.</p>
  
  <pre><code>if exists(...)
  begin
    ... -- update
  end
  else
  begin
    ... -- insert
  end
  </code></pre>