SQL Server 2005/2008 Group By statement with parameters without using dynamic SQL?

前端 未结 2 1487
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 12:20

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. <

相关标签:
2条回答
  • 2021-01-15 12:44

    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
    
    0 讨论(0)
  • 2021-01-15 12:52

    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.

    0 讨论(0)
提交回复
热议问题