Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T SQL case statement with primary and secondary order by parameter

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.

like image 982
CyberHawk Avatar asked Feb 06 '13 10:02

CyberHawk


People also ask

Can we use ORDER BY in CASE statement in SQL?

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 .

How do you use ORDER BY in CASE statement?

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.

Can you have multiple conditions in a CASE statement?

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.


1 Answers

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.

like image 102
Andrey Gordeev Avatar answered Sep 21 '22 23:09

Andrey Gordeev