I am passing two parameters:
@Column and @Direction, both of them are nvarchar(50)
I want to change the order by of the select query from the values inside the parameters.
For example,
if @Column = Name and @Direction = 'Desc' then order by Name desc
if @Column = Name and @Direction = 'Asc' then order by Name asc
if @Column = Type and @Direction = 'Desc' then order by Type desc
if @Column = Type and @Direction = 'Asc' then order by Type asc
My table is called Cars.
it has three columns: CarId, Name, Type
I tried to do this but it doesn’t return the right result (as if order by is ignored)
select * from Cars
order by
case
when @SortColumn = 'Type' and @SortDir = 'Desc' then 1
when @SortColumn = 'Type' and @SortDir = 'Desc' then 1
when @SortColumn = 'Name' and @SortDir = 'Asc' then 3
when @SortColumn = 'Name' and @SortDir = 'Asc' then 3, end asc
CASEis an expression that yields a single value. It can’t be used for control of flow like you might do in other languages or you might try withIF. You can’t useIFwithin a query either.The following treats each condition separately. If the conditions don’t match, the result for that expression is NULL, which is ignored in any ordering. So the order of these clauses is irrelevant, since only the ones where all conditions are true will be observed:
These can probably be combined somewhat, but I don’t know the data types, so this is probably safest. If the data types are the same, then:
You can’t collapse much further because you can’t do conditional
ASCvs.DESCin one expression. But you can simplify in other ways, e.g. the following queries will yield the same results as above, even though in some cases the order by will attempt to do (say)ORDER BY Type DESC, Type DESC– I’m not 100% sure if the optimizer simplifies that as redundant but it should collapse to a single sort operator (when required – sometimes this query could yield an inherent sort based on the index used to satisfy the query).…or…
You could also consider dynamic SQL since, if this gets much more complex, there is a lot of maintenance here.
Of course this can introduce other issues (maintainability of the rest of the query, plan cache bloat…)