我使用的是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
答案 0 :(得分: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
的索引,那么这可能会更有效。