Is there a way to write SQL Server Stored Procedure which to be strongly typed ( i.e. returning known result set of columns ) and having its group statement to be dynamic. <
You can group on a constant which might be useful
SELECT
SUM(Column0),
CASE @MyVar WHEN 'Column1' THEN Column1 ELSE '' END AS MyGrouping
FROM
Table1
GROUP BY
CASE @MyVar WHEN 'Column1' THEN Column1 ELSE '' END
Edit: For datatype mismatch and multiple values and this allows you to group on both columns...
SELECT
SUM(Column0),
CASE @MyVar WHEN 'Column1' THEN Column1 ELSE NULL END AS Column1,
CASE @MyVar WHEN 'Column2' THEN Column2 ELSE NULL END AS Column2
FROM
Table1
GROUP BY
CASE @MyVar WHEN 'Column1' THEN Column1 ELSE NULL END,
CASE @MyVar WHEN 'Column2' THEN Column2 ELSE NULL END
You are about to shoot yourself in the foot and are asking for a bigger bullet.
The only sensible approach to this is to separate the IF into a T-SQL flow control statement:
IF (0 = @MyVar)
SELECT SUM(Column0) FROM Table1 GROUP BY Column1;
ELSE IF (1 = @MyVar)
SELECT SUM(Column0) FROM Table1 GROUP BY Column2;
ESLE IF (2 = @myVar)
SELECT SUM(Column0) FROM Table1 GROUP BY Column3;
The last thing you want from the query optimizer is to generate a plan that has to GROUP BY a condition that is determined by a variable.