title: Dynamically merge the two tables using primary key
body: <p>I am trying to write a procedure where I can dynamically merge a number of staging+destination tables, each with different column names and primary keys.</p>
  
  <p>Is there a way to merge by extracting the primary key constraint?</p>
  
  <p>I envisioned doing a dynamic SQL statement which looked like this:</p>
  
  <pre><code>'MERGE
     ' + @DestinationTable + ' Dest
  USING
     ' + @StagingTable ' Staging
  ON
     ' + @JoinConditions + '
  WHEN NOT MATCHED THEN
     INSERT INTO
        Dest
     SELECT
        *
     FROM
        Staging
  WHEN MATCHED THEN
     UPDATE
        Dest
     SET
        ' + @UpdateStatement
  </code></pre>
  
  <p>Where <code>@DestinationTable</code> is a string parameter with the table name, <code>@StagingTable</code> is the same, <code>@JoinConditions</code> is a string which is of the format</p>
  
  <pre><code>Staging.ColumnName = Dest.ColumnName
  </code></pre>
  
  <p>for each key column, and <code>@UpdateStatement</code> is of the same format except with non-key columns.</p>
  
  <p>It doesn't look pretty, but this is how I foresee it working.</p>