sql案例按特定顺序和方向排序

5f0d552i  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(362)

我有一个表,需要按@sortby和@sortdirection对字段进行排序,
对于id,priorityid,statetype(列类型为int)结果是可以的,但是对于title(nvarchar),查询结果是: Conversion failed when converting the nvarchar value 'Title Column value' to data type int. 查询:

CASE 
                WHEN @SortDirection = 'ASC' THEN
                 CASE @SortBy
                    WHEN 'ID' THEN ID --int
                    WHEN 'Title' THEN Title  --nvarchar
                    WHEN 'PriorityID' THEN [Priority] --int
                    WHEN 'stateType' THEN [state] --int

                 end
              END ASC
              ,case WHEN @SortDirection = 'DESC' THEN
                CASE @SortBy
                    WHEN 'ID' THEN ID 
                    WHEN 'Title' THEN Title 
                    WHEN 'Priority' THEN [Priority]
                    WHEN 'state' THEN [state]
                END
            END DESC
e4yzc0pl

e4yzc0pl1#

类型不同,这是 case 表达。最简单的方法是另一种 case 对于每种可能性:

ORDER BY (CASE WHEN @SortDirection = 'ASC' AND @SortBy = 'ID' THEN ID END) ASC,
         (CASE WHEN @SortDirection = 'ASC' AND @SortBy = 'Title' THEN Title END) ASC,
         . . .

相关问题