Wednesday, July 25, 2012

Creating custom sort rules for SQL Server

-- Create a Location table 
DECLARE @LOCATION TABLE 
  ( 
     ID           INT IDENTITY(1, 1), 
     LocationName VARCHAR(50) 
  ) 

-- Insert dummy data 
INSERT INTO @Location
SELECT 'Chitoor'  UNION 
SELECT 'Idappadi'  UNION 
SELECT 'Salem'   UNION 
SELECT 'Savadipalayam' UNION 
SELECT 'Sankri'   UNION 
SELECT 'Morasapatti' UNION 
SELECT 'Polampatti' 

-- SELECT with plain our custom sort rules 
SELECT * 
FROM   @Location 
ORDER  BY CASE LocationName 
            WHEN 'Salem' THEN 1 
            WHEN 'Idappadi' THEN 2 
            WHEN 'Chitoor' THEN 3 
            WHEN 'Savadipalayam' THEN 4 
            ELSE 5000 
          END 
The column value which have the sort order, will order by the sort value in ascending.
If the column value which didn't have no sort order will order first Try checking by removing the else part.
If we want to use like clause in the ORDER BY statement, then how?
Move the sort columnName from case to when
SELECT * 
FROM   @Location 
ORDER  BY CASE  
            WHEN LocationName = 'Salem' THEN 1 
            WHEN LocationName = 'Idappadi' THEN 2 
            WHEN LocationName LIKE '%C%' THEN 3 
            WHEN LocationName =  'Savadipalayam' THEN 4 
            ELSE 5000 
          END 

No comments: