title: SELECT dynamic columns GROUP BY dynamic columns
body: <p>I need to accomplish the following in the stored procedure:</p>
  
  <ol>
  <li>Pass parameterized column names.</li>
  <li>Select the parameterized column names and provide total group by selected columns.</li>
  </ol>
  
  <p>Code: </p>
  
  <pre><code>CREATE PROCEDURE sproc (
    @column1 NVARCHAR(MAX),
    @column2 NVARCHAR(MAX),
    @startdate DATE,
    @enddate DATE ) AS
  
  BEGIN
  
    DECLARE @sqlquery NVARCHAR(MAX) = 'SELECT @column1, @column2, SUM(amountcolumn)
                                         FROM tablename
                                        WHERE column3 = ''@value3'',
                                              datecolumn BETWEEN ''@startdate'' AND ''@enddate''
                                     GROUP BY @column1, @column2';
  
    DECLARE @params NVARCHAR(MAX) = '@column1 VARCHAR(MAX),
                                     @column2 VARCHAR(MAX),
                                     @startdate DATE,
                                     @enddate  DATE';
  
    EXEC sp_sqlexec @sqlquery, @params,
         @column1 = @column1,
         @column2 = @column2,
         @startdate = @startdate,
         @enddate = @enddate;
  
  END
  
  GO
  </code></pre>