I have the following snippet from a SQL statements
ROW_NUMBER() OVER (ORDER BY CASE
WHEN @SortBy = 'column1 ASC' THEN cast(column1 AS sql_variant)
WHEN @SortBy = 'column2 ASC' THEN cast(column2 AS sql_variant)
WHEN @SortBy = 'column3 ASC' THEN cast(column3 AS sql_variant)
WHEN @SortBy = 'column4 ASC' THEN cast(column4 AS sql_variant)
ELSE NULL
END ASC,
CASE
WHEN @SortBy = 'column1 DESC' THEN cast(column1 AS sql_variant)
WHEN @SortBy = 'column2 DESC' THEN cast(column2 AS sql_variant)
WHEN @SortBy = 'column3 DESC' THEN cast(column3 AS sql_variant)
WHEN @SortBy = 'column4 DESC' THEN cast(column4 AS sql_variant)
ELSE NULL
END DESC) AS RowNumber
It works, but it’s quite repetitive, is there a way to make the ASC/DESC dynamic as well, so I don’t need the duplicated CASE statement?
One way you could do this would be to define the column alias at a different level so you can reference it twice without repeating the expression.
I would consider using dynamic SQL for this instead though. This kind of catch all query will kill the idea of getting a good plan that can use indexes to avoid a sort.