如何使 order by 子句动态化

How to make order by clause dynamic

我正在使用 SQL Server 2008,我想根据输入列名称和排序顺序 (asc/desc) 对数据进行排序。如何使下面的查询动态化?

DECLARE @iColumnName VARCHAR(24);
DECLARE @iSortOrder VARCHAR(10);

SET @iColumnName = 'ReceiptLocation'; -- ReceiptLocation/DeliverLocation/NominationNbr
SET @iSortOrder = 'DESC'; -- DESC / ASC

SELECT sum(NominationNbr)
    ,sum(ReceiptLocation)
    ,sum(DeliverLocation)
FROM tables
GROUP BY NominationNbr
    ,ReceiptLocation
    ,DeliverLocation
ORDER BY CASE @iColumnName
        WHEN 'ReceiptLocation'
            THEN ReceiptLocation
        WHEN 'DeliverLocation'
            THEN DeliverLocation
        ELSE NominationNbr
        END   

        CASE @iSortOrder
        WHEN 'DESC'
            THEN DESC
        ELSE ASC
        END

你需要把两者结合起来。我会建议这个相当笨重的代码:

ORDER BY (CASE WHEN @iColumnName = 'ReceiptLocation' AND @iSortOrder = 'DESC'
               THEN ReceiptLocation
          END) DESC,
         (CASE WHEN @iColumnName = 'ReceiptLocation' 
               THEN ReceiptLocation
          END) ASC,
         (CASE WHEN @iColumnName = 'DeliverLocation' AND @iSortOrder = 'DESC'
               THEN DeliverLocation
          END) DESC,
         (CASE WHEN @iColumnName = 'DeliverLocation' 
               THEN DeliverLocation
          END) ASC,
         (CASE WHEN @iSortOrder = 'DESC'
               THEN NominationNbr
          END) DESC,
         NominationNbr ASC

每个 CASE 语句都是一个单独的订单代码。但是,如果不匹配,则值为 NULL,因此如果不匹配,该键不会执行任何操作。

您也可以使用动态 SQL 来实现。如果您有一个简单的查询和可用于 ORDER BY.

的索引,那会更有效