title: Sort temp table in SQL Server
body: <p>I have a temp table in which I have a <code>SortOrder</code> column. Initially while inserting data in it I sort the data while inserting </p>
  
  <pre><code>INSERT INTO #MainCalcTemp
      SELECT  
          ItemId, ItemDesc, Quantity, Rate, Frequency,
          Annual, BasedOn, ProductCode, CalculationID, SortOrder 
      FROM 
          OneTimeFeesDocTemplate
      ORDER BY 
          SortOrder ASC
  </code></pre>
  
  <p>Now I add some data dynamically to it by using below SQL</p>
  
  <pre><code>INSERT INTO #MainCalcTemp
      SELECT 
          ItemID, ItemDesc, quantity, Rate, '', Annual, '', 'PHR', '', 2
      FROM
          #PackageInfoPHR 
      WHERE
          ItemID IN ('1PHR', '2PHR', '3PHR', '4PHR', '5PHR', '6PHR', '7PHR', '8PHR', '9PHR', '10PHR')
  </code></pre>
  
  <p>I added the items with the <code>SortOrder = 2</code>. I need to sort the <code>#MainCalcTemp</code> table again while inside the stored procedure to output the data in a sorted way since the additional items I am adding manually are coming out at the top.</p>
  
  <p>Can someone please tell me how to sort a temp table inside a stored procedure on demand so the new items that I add show up as number 2 and not on the top and I can add more items to it at desired position and sort it again.</p>
  
  <p>Thanks</p>