Ehsan Mahpour’s Weblog

How to sort the SQL results dynamically (dynamic ORDER BY)

by mahpour on May.08, 2007, under Uncategorized

The solution is using CASE statement in your select query .

Here’s a sample:
 
DECLARE @sortColumn VARCHAR(255)
SELECT @sortColumn = ‘title’

SELECT * FROM asset
ORDER BY
CASE
WHEN @sortColumn = ‘title’ THEN title
WHEN @sortColumn = ’start_date’ THEN start_date
WHEN @sortColumn = ‘asset_id’ THEN asset_id
ELSE title
END


Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...