Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL
Expertise: Intermediate
Jul 6, 2009

Selecting Sort Order at Runtime

You can select which column to sort a SELECT statement by at runtime, using just one parameter. To do this, declare one parameter and use it with a CASE command. Then, include each column you might want to sort by as a CASE condition, for example:

Declare @Parameter char(1)

SELECT
  ID,
  Descripcion,
  Stock,
  Price
  Case @Parameter
    when 'I' then ID
    when 'D' then Descripcion
    when 'S' then Stock
    when 'P' then Price
  END AS SortColumn
FROM Products
ORDER BY SortColumn

Using this method, you can avoid writing if clauses for each possible sort order.

Magno Canto
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date