Solving development problems  |  About this blog

Archive for the ‘order by parameter’ tag

ORDER BY parameter (conditional)

This scripts shows how you can sort by some parameter in Transact SQL:

DECLARE @SortOrder tinyint
SET @SortOrder = 2

SELECT CompanyName,
       ContactName,
       ContactTitle
FROM Customers
ORDER BY CASE WHEN @SortOrder = 1 THEN CompanyName
              WHEN @SortOrder = 2 THEN ContactName
              ELSE ContactTitle
         END

Written by Avivo

February 23rd, 2010 at 5:39 pm