I was looking into sorting tables by a column designated given some input, and from what I’ve found, there is no easy way to do this. The best I’ve found is a 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 having a CASE statement like that? If the table gets bigger and more columns need to be sorted by, this could become messy.
The only way I’ve been able to do this is by just concatenating a big SQL string, which sort of defeats the advantages of Stored Procedures, and makes the SQL hard to write and maintain.
You have two choices:
As you have implemented above
Or generate dynamic sql and execute using
sp_executesql