I have a problem with my SQL statement: I use SELECT statement and then CASE when I use order by.
SELECT .....
ORDER BY
CASE WHEN @sort = 'ND' THEN name END DESC,
CASE WHEN @sort = 'NA' THEN name END,
CASE WHEN @sort = 'AD' THEN (isAuthorized) END DESC,
CASE WHEN @sor = 'AA' THEN (isAuthorized) END
isAuthorized is a BIT value, so I would like to use secondary order by there.
I tried something like:
SELECT .....
ORDER BY
CASE WHEN @sort = 'ND' THEN name END DESC,
CASE WHEN @sort = 'NA' THEN name END,
CASE WHEN @sort = 'AD' THEN (isAuthorized, name ) END DESC,
CASE WHEN @sort = 'AA' THEN (isAuthorized, name ) END
But it doesn't work.
I use SQL server 2008.
Any help would be greatly appreciated.
Although it is most often used there, CASE is not limited to SELECT statements. For example, you can use it in clauses like IN , WHERE , HAVING , and ORDER BY .
CASE Syntax: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.
You can have multiple WHEN clauses in a single CASE expression. THEN: the result to return if the WHEN clause's condition is true. You must have one THEN clause for each WHEN clause in your CASE expression.
If you want order the result set first by name
and then by isAuthorized
when @sort = ND
use this query:
SELECT .....
ORDER BY
CASE WHEN @sort = 'ND' THEN name END DESC,
CASE WHEN @sort = 'ND' THEN isAuthorized END
You can combine CASE
clauses. I hope you got the idea.
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