I understand that I can use variables in the order by section of sql queries like this:
order by case when @var1 = 'priority' then priority end desc, case when @var2 = 'report_date' then report_date end asc
But how do I use variables for the asc and desc sections too?
To sort in ascending or descending order we can use the keywords ASC or DESC respectively. To sort according to multiple columns, separate the names of columns by the (,) operator. Now consider the above database table and find the results of different queries.
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name ). You can modify the sorting order (ascending or descending) separately for each column.
without Dynamic SQL
each option it's clause for example:
ORDER BY case when @var1 = 'priority asc' THEN priority END ASC , case when @var1 = 'priority desc' then priority end DESC, case when @var2 = 'report_date asc' then report_date end ASC, case when @var2 = 'report_date desc' then report_date end DESC
Assuming your variable @var3
stores 'ASC'
or 'DESC'
keywords, you can write something like this:
order by case when @var1 = 'priority' and @var3 = 'DESC' then priority end DESC, case when @var1 = 'priority' and @var3 = 'ASC' then priority end ASC, case when @var2 = 'report_date' and @var3 = 'ASC' then report_date end ASC, case when @var2 = 'report_date' and @var3 = 'DESC' then report_date end DESC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With