Case statement for Order By clause with Desc/Asc sort

后端 未结 3 984
感情败类
感情败类 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:40

    You need to split your ORDER BY in two parts:

    SELECT *
    FROM
        TableName
    WHERE
    ORDER BY 
        (CASE @OrderByColumn
        WHEN 1 THEN Forename
        END) DESC -- Forename --> descending
    ,   (CASE @OrderByColumn
        WHEN 2 THEN Surname
        END) ASC -- Surname --> ascending
    

提交回复
热议问题