We have a stored procedure where we want to dynamically let the user choose which column to sort the result by, and in which order (ascending/descending). Currently, we have the following ORDER BY
clause, but I'm sure it can be optimized. How?
ORDER BY
CASE WHEN @OrderBy = 'salvnummer' AND @OrderByDirection = 'DESC' THEN salvnummer END DESC,
CASE WHEN @OrderBy = 'salvnummer' AND @OrderByDirection = 'ASC' THEN salvnummer END, --ASC
CASE WHEN @OrderBy = 'entreprenaddel' AND @OrderByDirection = 'DESC' THEN entreprenaddel END DESC,
CASE WHEN @OrderBy = 'entreprenaddel' AND @OrderByDirection = 'ASC' THEN entreprenaddel END, --ASC
CASE WHEN @OrderBy = 'sektion' AND @OrderByDirection = 'DESC' THEN sektion END DESC,
CASE WHEN @OrderBy = 'sektion' AND @OrderByDirection = 'ASC' THEN sektion END, --ASC
CASE WHEN @OrderBy = 'tid' AND @OrderByDirection = 'DESC' THEN tid END DESC,
CASE WHEN @OrderBy = 'tid' AND @OrderByDirection = 'ASC' THEN tid END --ASC
Both input parameters are currently varchars
.