title: Order by and Different Types in a CASE
body: <p>I have a requirement to order a result set by a column, based on an Integer input into a parameter.</p>
  
  <p>Problem is, I need to use a CASE for the OrderBy, and it seems the code accepts the first 'TYPE' in the case column... any other types fail.</p>
  
  <p>My code is like this:</p>
  
  <pre><code>    WITH error_table AS  
   (  
    SELECT Row_Number() OVER   
     (ORDER BY  
          CASE @orderBy
              WHEN 1 THEN received_date  -- Last Rx'd message  
              WHEN 2 THEN message_id -- Message Id  
              WHEN 3 THEN zibmat.short_name -- Message action type  
              WHEN 4 THEN error_action.short_name -- Status type  
              WHEN 5 THEN ime.[allocated_date] -- Allocated Date  
              ELSE received_date
      END) AS RowNumber   
  
     ,ime.[ijis_message_error_id]  
        ,ime.[message_id]  
        ,ime.[message_version] 
  </code></pre>
  
  <p>So, when OrderBy is 1, it works. It sorts by rx_date... but when I sent it a 2, it fails with a data time conversion error.</p>
  
  <p>It looks like all the types must be the same...</p>
  
  <p>Sending a 5 works fine, as that's a date time too.</p>
  
  <p>Is there a way I can fix this?</p>