Selecting Sort Order at Runtime

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 SortColumnFROM ProductsORDER BY SortColumn

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


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist