title: SQL Server: Inline Table-Value UDF vs. Inline View
body: <p>I'm working with a medical-record system that stores data in a construct that resembles a spreadsheet--date/time in column headers, measurements (e.g. physician name, Rh, blood type) in first column of each row, and a value in the intersecting cell.  Reports that are based on this construct often require 10 or more of these measures to be displayed.  </p>
  
  <p>For reporting purposes, the dataset needs to have one row for each patient, the date/time the measurement was taken, and a column for each measurement.  In essence, one needs to pivot the construct by 90 degrees.</p>
  
  <p>At one point, I actually used SQL Server's PIVOT functionality to do just that.  For a variety of reasons, it became apparent that this approach wouldn't work.  I decided that I would use an inline view (IV) to massage the data into the desired format.  The simplified query resembles:</p>
  
  <pre><code>SELECT patient_id, 
         datetime, 
         m1.value AS physician_name, 
         m2.value AS blood_type, 
         m3.value AS rh
    FROM patient_table
  INNER JOIN ( complex query here
                WHERE measure_id=1) m1...
  INNER JOIN (complex query here
                WHERE measure_id=2) m2...
  LEFT OUTER JOIN (complex query here
                   WHERE measure_id=3) m3...
  </code></pre>
  
  <p>As you can see, in some cases these IVs are used to restrict the resulting dataset (INNER JOIN), in other cases they do not restrict the dataset (LEFT OUTER JOIN).  However, the 'complex query' part is essentially the same for each of these measure, except for the difference in measure_id. While this approach works, it leads to fairly large SQL statements, limits reuse, and exposes the query to errors.</p>
  
  <p>My thought was to replace the 'complex query' and WHERE clause with a Inline Table-Value UDF.  This would simplify the queries quite a bit, reduce errors, and increase code reuse.  The only question on my mind is performance.  Will the UDF approach lead to significant decreases in performance?  Might it improve matters?  </p>
  
  <p>Thanks for your time and consideration.</p>