I studied sorting tables by the column specified by input, and from what I found there is no easy way to do this. The best I have found is the switch statement:
SELECT Column1, Column2, Column3, Column4 FROM Table ORDER BY CASE WHEN @OrderBY = 'Column1' THEN Column1 WHEN @OrderBY = 'Column2' THEN Column2 WHEN @OrderBY = 'Column3' THEN Column3 WHEN @OrderBY = 'Column4' THEN Column4
Is it possible to do this without such a CASE statement? If the table gets larger and more columns need to be sorted, this can become messy.
The only way I was able to do this was to simply concatenate a large SQL string, which spoils the benefits of stored procedures and makes SQL difficult to write and maintain.
source share