Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Dynamic ordering without dynamic sql (See related posts)

DECLARE @order int
SET @order = 1
SELECT * FROM users
ORDER BY 
        CASE WHEN @order = 1 THEN [name] END DESC,
        CASE WHEN @order = 2 THEN [name] END ASC,
        CASE WHEN @order = 3 THEN [email] END DESC,
        CASE WHEN @order = 4 THEN [email] END ASC

set the @order to 1-4 to get specific order by clause, setting it to anything else give results as if no order by clause supplied

remember dynamic SQL (creating SQL in a string and then executing) can not be effectively cached so this is a much better option

You need to create an account or log in to post comments to this site.


Related Posts