动态排序依据和列排序

时间:2018-12-06 19:23:27

标签: sql sql-server common-table-expression

我必须在UI网格中显示数据,并从SQL Server 2014中的两个不同表中选择数据。

数据可以按来自UI代码的任何列进行排序,也可以按两个方向(ASC / DESC)进行排序。 UI代码也传递方向。

在我当前的实现中,我们使用CTE如下-

    ;WITH cte AS
    (SELECT ED.JobExecutionID
        , ED.RowNumber
        , ED.ErrorMessage
        , ED.RowData    
        , CASE 
            WHEN @SortKey = 'RowNumber' AND @SortDirection = 'Ascending' THEN ROW_NUMBER() OVER (ORDER BY ED.RowNumber ASC)
            WHEN @SortKey = 'RowNumber' AND @SortDirection = 'Descending' THEN ROW_NUMBER() OVER (ORDER BY ED.RowNumber DESC)
            WHEN @SortKey = 'ErrorMessage' AND @SortDirection = 'Ascending' THEN ROW_NUMBER() OVER (ORDER BY ED.ErrorMessage ASC)
            WHEN @SortKey = 'ErrorMessage' AND @SortDirection = 'Descending' THEN ROW_NUMBER() OVER (ORDER BY ED.ErrorMessage DESC)
            WHEN @SortKey = 'RowData' AND @SortDirection = 'Ascending' THEN ROW_NUMBER() OVER (ORDER BY ED.RowData ASC)
            WHEN @SortKey = 'RowData' AND @SortDirection = 'Descending' THEN ROW_NUMBER() OVER (ORDER BY ED.RowData DESC)
            ELSE ROW_NUMBER() OVER (ORDER BY  ED.RowNumber ASC)
         END AS SortRowNumber       
    FROM ExceptionDetails ED        
    JOIN ExecutionDetails IED ON IED.JobExecutionID = ED.JobExecutionID
    WHERE ED.JobExecutionID = @JobExecutionId
),
RESULTS AS  
    (SELECT * FROM cte) 
SELECT JobExecutionID
    , RowNumber
    , ErrorMessage
    , RowData
    , SortRowNumber
FROM RESULTS
WHERE SortRowNumber BETWEEN @StartRowNumber AND @EndRrowNumber
ORDER BY SortRowNumber

我希望摆脱CTE,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

您只需将案例表达式移动到ORDER BY中即可:

SELECT    ED.JobExecutionID
        , ED.RowNumber
        , ED.ErrorMessage
        , ED.RowData    
FROM ExceptionDetails ED        
JOIN ExecutionDetails IED ON IED.JobExecutionID = ED.JobExecutionID
WHERE ED.JobExecutionID = @JobExecutionId
ORDER BY CASE 
         WHEN @SortKey = 'RowNumber' AND @SortDirection = 'Ascending' THEN ROW_NUMBER() OVER (ORDER BY ED.RowNumber ASC)
         WHEN @SortKey = 'RowNumber' AND @SortDirection = 'Descending' THEN ROW_NUMBER() OVER (ORDER BY ED.RowNumber DESC)
         WHEN @SortKey = 'ErrorMessage' AND @SortDirection = 'Ascending' THEN ROW_NUMBER() OVER (ORDER BY ED.ErrorMessage ASC)
         WHEN @SortKey = 'ErrorMessage' AND @SortDirection = 'Descending' THEN ROW_NUMBER() OVER (ORDER BY ED.ErrorMessage DESC)
         WHEN @SortKey = 'RowData' AND @SortDirection = 'Ascending' THEN ROW_NUMBER() OVER (ORDER BY ED.RowData ASC)
         WHEN @SortKey = 'RowData' AND @SortDirection = 'Descending' THEN ROW_NUMBER() OVER (ORDER BY ED.RowData DESC)
         ELSE ROW_NUMBER() OVER (ORDER BY ED.RowNumber ASC)
         END