多个case表达式按顺序SQL Server

时间:2015-11-05 12:09:04

标签: sql sql-server stored-procedures

我有一个下面给出的存储过程,我必须动态地对结果进行排序,但它会产生语法错误。请告诉我正确的方法

SELECT *
FROM [TableName]
ORDER BY CASE @OrderBy
        WHEN 'DESC'
            THEN CASE @Sort
                    WHEN 'CreatedOn'
                        THEN CreatedOn
                    WHEN 'EmployeeName'
                        THEN EmployeeName
                    WHEN 'EmployeeCode'
                        THEN EmployeeCode
                    WHEN 'Country'
                        THEN Country
                    WHEN 'Location'
                        THEN Location
                    WHEN 'Skill'
                        THEN Skill
                    WHEN 'ProcessName'
                        THEN ProcessName
                    WHEN 'RoleName'
                        THEN RoleName
                    WHEN 'JoiningDate'
                        THEN JoiningDate
                    ELSE CreatedOn
                    END DESC
        ELSE CASE @Sort
                WHEN 'CreatedOn'
                    THEN CreatedOn
                WHEN 'EmployeeName'
                    THEN EmployeeName
                WHEN 'EmployeeCode'
                    THEN EmployeeCode
                WHEN 'Country'
                    THEN Country
                WHEN 'Location'
                    THEN Location
                WHEN 'Skill'
                    THEN Skill
                WHEN 'ProcessName'
                    THEN ProcessName
                WHEN 'RoleName'
                    THEN RoleName
                WHEN 'JoiningDate'
                    THEN JoiningDate
                ELSE CreatedOn
                END ASC
        END

1 个答案:

答案 0 :(得分:3)

您的语法错误是在DESC表达式中使用CASE。它用于限定排序顺序;在CASE内部无法理解。

此外,您还有潜在的运行时错误。 case表达式返回单个类型的单个值。因此,最好分别列出每个条件:

ORDER BY (CASE @OrderBy = 'DESC' AND @Sort = 'CreatedOn' THEN CreatedOn END) DESC,
         (CASE @OrderBy = 'DESC' AND @Sort = 'EmployeeName' THEN EmployeeName END) DESC,
         . . .
         (CASE @OrderBy = 'ASC' AND @Sort = 'CreatedOn' THEN CreatedOn END),
         (CASE @OrderBy = 'ASC' AND @Sort = 'EmployeeName' THEN EmployeeName END),
         . . .   

老实说,对于这种类型的查询,如果ORDER BY列上有索引,则动态SQL会更有效。