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