2015-09-28 90 views
1

我正在使用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 

回答

1

您需要将两者结合起来。我建议这个非常笨拙代码:

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的索引,那么这会更有效。