Is there a way to write a SELECT ... ORDER BY query so that the sort order is controlled by a variable? The solution I have is to use IF and run one query if the sort should be ascending and run the other query if it should be descending. This is in a stored procedure.
Here is what I am doing. Is there a way to do this in one statement?
Here is what I am doing. Is there a way to do this in one statement?
Code:
IF @sortDirection = 1
SELECT very, interesting, material
FROM aBunch of tables
ORDER BY
CASE
WHEN @sortField = 1 THEN very
WHEN @sortField = 2 THEN interesting
ELSE @sortField = 3 THEN material
END DESC
ELSE
SELECT very, interesting, material
FROM aBunch of tables
ORDER BY
CASE
WHEN @sortField = 1 THEN very
WHEN @sortField = 2 THEN interesting
ELSE @sortField = 3 THEN material
END ASC