Custom Sort Order - How to not duplicate the Case statement
You could multiply the sorting key by either +1 or -1 depending on whether ASC or DESC is requested:
SELECT ROW_NUMBER() OVER (ORDER BY
CASE WHEN @sortColumnName = 'Variety'
THEN
(CASE f.Variety
WHEN 'Fuji' THEN 1
WHEN 'Gala' THEN 2
ELSE 3
END)
END
* (CASE WHEN @sortDirection = 'ASC' THEN 1 ELSE -1 END)), *
FROM Fruits f
Since you're on SQL 2008, you could use a CTE:
;WITH CTE AS
(
SELECT
CASE WHEN @sortColumnName = 'Variety' THEN
CASE f.Variety
WHEN 'Fuji' THEN 1
WHEN 'Gala' THEN 2
ELSE 3
END
END AS sort_column,
*
FROM
Fruits F
)
SELECT
ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @sortDirection = 'DESC' THEN sort_column ELSE 0 END DESC,
CASE WHEN @sortDirection = 'ASC' THEN sort_column ELSE 0 END ASC),
type,
variety,
price
FROM
CTE
It's not as slick as the *-1 solution for this particular problem, but it can be adapted for other situations where you want to avoid code duplication.