Wednesday, March 20, 2013

CASE CONDITION in Order by CLAUSE MSSQL



I have an situation to get the output result with condition in order by clause as per user input. i have get a solution. here i will share my solution


SELECT
 ItemCode, ItemName, Price
FROM  
 Date.ItemMaster 
ORDER BY  <condition>

Solution1:

DECLARE @input int
SET @input=1
/*
1 -  means ascending order
2 -  means Descending order
*/
SELECT Itemcode, ItemName, PurchasePrice
FROM Data.ItemMaster
ORDER BY
      CASE WHEN @input=1 THEN itemName END ASC,
      CASE WHEN @input=2 THEN ItemName END DESC

In the above code we can change the sorting order as per user need.

No comments:

Post a Comment

Comment Here..