title: Comma-separated list of dynamic column names
body: <p>I would like to create a stored procedure in SQL Server 2012 with a comma-separated input parameter that will define which columns are selected. I will need to perform a simple calculation on some columns such as a SUM or AVG.  </p>
  
  <p>Sample data in table:</p>
  
  <pre><code>Amount Cost   Year Author
  15.00  11.00  2011 Lloyd Christmas
  17.00  50.00  2009 Billy Madison
  12.00  10.00  2010 Joe Dirt
  </code></pre>
  
  <p>I would execute the SP using syntax similar to this (can be dynamic if it makes the code easier):</p>
  
  <pre><code>exec StoredProc @CSV = 'Amount,Year'
  </code></pre>
  
  <p>What makes this difficult is that I need to do simple calculations on the columns selected.  </p>
  
  <pre><code>Select SUM([Amount]), AVG([YEAR]) 
  FROM TBL
  </code></pre>
  
  <p>Another example:</p>
  
  <pre><code>exec StoredProc @CSV = "Amount,Cost,Year"
  
  Select SUM([Amount]),SUM(Cost),AVG([YEAR]) 
  FROM TBL
  </code></pre>