Saturday, April 25, 2009

CASE Statement in ORDER BY Clause - ORDER BY using Variable

Stored Procedure takes variable OrderBy as input parameter.

SP uses EXEC (or sp_executesql) to execute dynamically build SQL.


This was taking big hit on performance. The issue was how to improve the performance as well as remove the logic of preparing OrderBy from application. The solution I came up was using multiple CASE statement. This solution is listed here in simple version using AdventureWorks sample database. Another challenge was to order by direction of ascending or descending direction. The solution of that issue is also displayed in following example. Test the example with different options for @OrderBy and @OrderByDirection.


Currently:

Database only solution:

USE AdventureWorks


GO

DECLARE @OrderBy VARCHAR(10)

DECLARE @OrderByDirection VARCHAR(1)

SET @OrderBy = 'State' ----Other options Postal for PostalCode,


---- State for StateProvinceID, City for City

SET @OrderByDirection = 'D' ----Other options A for ascending,

---- D for descending

SELECT AddressID, City, StateProvinceID, PostalCode


FROM person.address

WHERE AddressID < 100

ORDER BY

CASE WHEN @OrderBy = 'Postal'

AND @OrderByDirection = 'D'


THEN PostalCode END DESC,

CASE WHEN @OrderBy = 'Postal'

AND @OrderByDirection != 'D'

THEN PostalCode END,


CASE WHEN @OrderBy = 'State'

AND @OrderByDirection = 'D'

THEN StateProvinceID END DESC,

CASE WHEN @OrderBy = 'State'


AND @OrderByDirection != 'D'

THEN StateProvinceID END,

CASE WHEN @OrderBy = 'City'

AND @OrderByDirection = 'D'


THEN City END DESC,

CASE WHEN @OrderBy = 'City'

AND @OrderByDirection != 'D'

THEN City END


GO

No comments:

Post a Comment