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

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 comment

Please be polite and on topic. Your e-mail will never be published.

You must be logged in to post a comment.