Parameter-driven ASC/DESC Sort ( CASE in ORDER BY )

This post is came up from a MSDN forum post that discussed last night . Problem was to write CASE in ORDER BY cluase without using dynamic sql. This is my solution that I just want to share it.


DECLARE @SortDesc BIT = 1;
SELECT  *
FROM    Sales.SalesOrderHeader
ORDER BY
CASE WHEN @SortDesc = 1 THEN SalesOrderID END DESC ,
CASE WHEN ISNULL(@SortDesc, 0) <> 1 THEN SalesOrderID END ASC ;

Advertisements