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

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s