Case statement for Order By clause with Desc/Asc sort

后端 未结 3 987
感情败类
感情败类 2021-02-14 16:07
SELECT *
FROM
    TableName
WHERE
ORDER BY 
    CASE @OrderByColumn
    WHEN 1 THEN Forename
    WHEN 2 THEN Surname
    END;

I have a statement like a

3条回答
  •  梦如初夏
    2021-02-14 16:44

    You need two clauses in the order by:

    ORDER BY (CASE WHEN @OrderByColumn = 1 and @Dir = 'ASC' THEN Forename
                   WHEN @OrderByColumn = 2 and @Dir = 'ASC' THEN Surname
              END) ASC,
             (CASE WHEN @OrderByColumn = 1 and @Dir = 'DESC' THEN Forename
                   WHEN @OrderByColumn = 2 and @Dir = 'DESC' THEN Surname
              END) DESC
    

提交回复
热议问题