title: C# Update SQL Server table based on results from a select statement
body: <p><strong>Background</strong></p>
  
  <p>I'm trying to update a specific set of rows returned from a select statement in a table. The table consists of an id and value. The ids are not unique because there is a column indicating a revision.</p>
  
  <p><strong>Currently</strong></p>
  
  <p>What I'm looking to do is update the values for the <em>most recent</em> revision per id from within C#.</p>
  
  <p>So far, the select statement I have written returns all the ids and values for the most recent revision.</p>
  
  <pre><code>SELECT id, value
  FROM table1 AS T1
  WHERE createdOn = (SELECT MAX(createdOn)
                     FROM table1 AS T2
                     WHERE T1.id = T2.id)
  </code></pre>
  
  <p>I have created SQL parameters in C# which contain the id and the value. I will use the id to identify which row I need to insert the new value for. I will of course use the value as the value to be inserted at that id.</p>
  
  <p>Here are the parameters:</p>
  
  <pre><code>SqlParameter idParameter = new SqlParameter("@id", SqlDbType.Int);
  SqlParameter valueParameter = new SqlParameter("@updatedValue", SqlDbType.NVarChar);
  </code></pre>
  
  <p>Within C# I have a dictionary used to store the ids and values that have already been updated to their new values in the code before.</p>
  
  <pre><code>Dictionary&lt;int, string&gt; updatedValues = new Dictionary&lt;int, string&gt;();
  </code></pre>
  
  <p>I intend to loop through this dictionary and set the SQL parameters to that of the current key and value in the dictionary. The code I currently have looks like this:</p>
  
  <pre><code>foreach (var entry in updatedValues)
  {
      idParameter.Value = entry.Key;
      valueParameter.Value = entry.Value;
  
      //perform sql update command
  }
  </code></pre>
  
  <p>As indicated by the comment I believe it is here that the SQL update command needs to be executed.</p>
  
  <p>Guidance as to how to do this and what the SQL query string would look like to make sure that only the <em>most recent</em> revision is updated would be much appreciated.</p>
  
  <p><strong>Things I've tried</strong></p>
  
  <p>I've tried modifying my SQL query to use joins to then hopefully be easier to modify into an update command, with no luck. I have also attempted to insert the results from my query into a temporary table and then try to perform the update on the temporary table. However I then reach another problem when trying to get the temporary table into the actual table.</p>
  
  <p>Thanks in advance</p>
  
  <p>Side note: I have modified variable names in order to try and allow others to adapt to their code easier if a solution works for them well too</p>