我在存储过程中有以下SQL。有没有一种方法可以删除IF语句,并将’ASC’/’DESC’选项作为变量传递?
我知道我可以用多种不同的方式进行查询,或者返回一个表并在外部对其进行排序等。我只想知道是否可以避免重复CASE语句。
IF @sortOrder = 'Desc' BEGIN SELECT * FROM #t_results ORDER BY CASE WHEN @OrderBy = 'surname' THEN surname END DESC, CASE WHEN @OrderBy = 'forename' THEN forename END DESC, CASE WHEN @OrderBy = 'fullName' THEN fullName END DESC, CASE WHEN @OrderBy = 'userId' THEN userId END DESC, CASE WHEN @OrderBy = 'MobileNumber' THEN MSISDN END DESC, CASE WHEN @OrderBy = 'DeviceStatus' THEN DeviceStatus END DESC, CASE WHEN @OrderBy = 'LastPosition' THEN LastPosition END DESC, CASE WHEN @OrderBy = 'LastAlert' THEN LastAlert END DESC, CASE WHEN @OrderBy = 'LastCommunication' THEN LastCommunication END DESC, CASE WHEN @OrderBy = 'LastPreAlert' THEN LastPreAlert END DESC END ELSE BEGIN SELECT * FROM #t_results ORDER BY CASE WHEN @OrderBy = 'surname' THEN surname END DESC, CASE WHEN @OrderBy = 'forename' THEN forename END DESC, CASE WHEN @OrderBy = 'fullName' THEN fullName END DESC, CASE WHEN @OrderBy = 'userId' THEN userId END DESC, CASE WHEN @OrderBy = 'MobileNumber' THEN MSISDN END DESC, CASE WHEN @OrderBy = 'DeviceStatus' THEN DeviceStatus END DESC, CASE WHEN @OrderBy = 'LastPosition' THEN LastPosition END DESC, CASE WHEN @OrderBy = 'LastAlert' THEN LastAlert END DESC, CASE WHEN @OrderBy = 'LastCommunication' THEN LastCommunication END DESC, CASE WHEN @OrderBy = 'LastPreAlert' THEN LastPreAlert END DESC END END
传入@OrderBy int,其中正数是ASC,负数是DESC,实际数字是要排序的列
SELECT dt.yourColumn1 ,dt.yourColumn2 ,dt.yourColumn3 ,CASE WHEN @OrderBy>0 THEN dt.SortBy ELSE NULL END AS SortByAsc ,CASE WHEN @OrderBy<0 THEN dt.SortBy ELSE NULL END AS SortByDesc FROM (SELECT yourColumn1 ,yourColumn2 ,yourColumn3 ,CASE WHEN ABS(@OrderBy) = 1 THEN surname WHEN ABS(@OrderBy) = 2 THEN forename WHEN ABS(@OrderBy) = 3 THEN fullName WHEN ABS(@OrderBy) = 4 THEN CONVERT(varchar(10),userId) WHEN ABS(@OrderBy) = 5 THEN CONVERT(varchar(10),MobileNumber WHEN ABS(@OrderBy) = 6 THEN DeviceStatus WHEN ABS(@OrderBy) = 7 THEN LastPosition WHEN ABS(@OrderBy) = 8 THEN CONVERT(varchar(23),LastAlert,121) WHEN ABS(@OrderBy) = 9 THEN CONVERT(varchar(23),LastCommunication,121) WHEN ABS(@OrderBy) =10 THEN CONVERT(varchar(23),LastPreAlert,121) ELSE NULL END AS SortBy FROM YourTablesHere WHERE X=Y ) dt ORDER BY SortByAsc ASC, SortByDesc DESC
只需确保您构建的字符串能够正确排序,请注意,我使用’YYYY-MM-DD hh:mm:ss.mmm’作为日期,并将数字放入字符串中。我们通常将多个列放在一起,因此,如果您按姓氏排序,也使用姓氏,等等。请注意,如果您合并多个列,则需要用零或空格填充。
如果您不希望将SortByAsc和SortByDesc列包含在结果集中,请将整个内容包装在派生表中。