title: When to use CTE in Stored Procedure
body: <pre><code>SELECT 
      tchart.*
  INTO
      #OrderSections
  FROM 
      Order.Charts tchart
  INNER JOIN
      (
      SELECT  
          tchart.ID,
          tchart.ORCode,
          tchart.SectionalDistance,
          row_number() OVER( PARTITION BY rrs.ORCode ORDER BY tchart.VendorTimestampUTC DESC, tchart.InsertedTimestampUTC DESC, tchart.ID DESC ) AS RecordIndex
      FROM
          #OrderStaging rrs
      INNER JOIN
          Order.Charts tchart
      ON
          rrs.ORCode = tchart.ORCode
      ) AS Latest_tchart
  ON
      tchart.ID = Latest_tchart.ID
  WHERE
      Latest_tchart.RecordIndex   = 1;
  </code></pre>
  
  <hr>
  
  <pre><code>    With cte as(    
      SELECT  
          tchart.ID,
          tchart.ORCode,
          tchart.SectionalDistance,
          row_number() OVER( PARTITION BY rrs.ORCode ORDER BY tchart.VendorTimestampUTC DESC, tchart.InsertedTimestampUTC DESC, tchart.ID DESC ) AS RecordIndex
      FROM
          #OrderStaging rrs
      INNER JOIN
          Order.Charts tchart
      ON
          rrs.ORCode = tchart.ORCode) 
      SELECT 
          cte.*
      INTO
          #OrderSections
      FROM 
          cte
      WHERE 
          RecordIndex = 1  
  </code></pre>
  
  <p>Would the CTE have a great impact specially in a stored procedure?</p>