在日常的報表中常用到排序,有些是多字段的升,降序,一般有兩種方法,如下所示:
CREATE TABLE #TMP
(
row int,
id nvarchar(10),
des nvarchar(20)
)
GO
INSERT INTO #TMP(row, id, des)
SELECT 1, '1', '30'
UNION SELECT 2, '2', '10'
UNION SELECT 3, '1', '10'
UNION SELECT 4, '3', '15'
--'1'=>row desc,'2'=>id asc,row desc '3'=>id asc, des desc
DECLARE @OrderType nvarchar(1)
SET @OrderType='3'
--EXEC作法
DECLARE @sqlstr nvarchar(200)
SET @sqlstr='SELECT * FROM #TMP'
IF @OrderType='1'
SET @sqlstr=@sqlstr+' ORDER BY row DESC'
ELSE IF @OrderType='2'
SET @sqlstr=@sqlstr+' ORDER BY id, row DESC'
ELSE IF @OrderType='3'
SET @sqlstr=@sqlstr+' ORDER BY id, des DESC'
EXEC(@sqlstr)
--以上方法不易閱讀及維護,還有額外變量
SELECT *
FROM #TMP
ORDER BY CASE WHEN @OrderType='1' THEN row END DESC,
CASE WHEN @OrderType='2' THEN id END,
CASE WHEN @OrderType='2' THEN row END DESC,
CASE WHEN @OrderType='3' THEN id END,
CASE WHEN @OrderType='3' THEN DES END DESC;
--結果一致,CASE WHEN 方法不存在以上問題
(
row int,
id nvarchar(10),
des nvarchar(20)
)
GO
INSERT INTO #TMP(row, id, des)
SELECT 1, '1', '30'
UNION SELECT 2, '2', '10'
UNION SELECT 3, '1', '10'
UNION SELECT 4, '3', '15'
--'1'=>row desc,'2'=>id asc,row desc '3'=>id asc, des desc
DECLARE @OrderType nvarchar(1)
SET @OrderType='3'
--EXEC作法
DECLARE @sqlstr nvarchar(200)
SET @sqlstr='SELECT * FROM #TMP'
IF @OrderType='1'
SET @sqlstr=@sqlstr+' ORDER BY row DESC'
ELSE IF @OrderType='2'
SET @sqlstr=@sqlstr+' ORDER BY id, row DESC'
ELSE IF @OrderType='3'
SET @sqlstr=@sqlstr+' ORDER BY id, des DESC'
EXEC(@sqlstr)
--以上方法不易閱讀及維護,還有額外變量
SELECT *
FROM #TMP
ORDER BY CASE WHEN @OrderType='1' THEN row END DESC,
CASE WHEN @OrderType='2' THEN id END,
CASE WHEN @OrderType='2' THEN row END DESC,
CASE WHEN @OrderType='3' THEN id END,
CASE WHEN @OrderType='3' THEN DES END DESC;
--結果一致,CASE WHEN 方法不存在以上問題
[注:ORDER BY 中使用CASE WHEN 是可以加 DESC 的]