alpha 列的条件 SQL ORDER BY ASC/DESC
在 MS SQL Server 2008 R2 中编写存储过程,我想避免使用 DSQL...
Writing a stored procedure in MS SQL Server 2008 R2, I want to avoid using DSQL...
我希望排序方法(ASC 或 DESC)是有条件的.
I would like the sort method (ASC or DESC) to be conditional.
现在,对于数字列,我将简单地使用 case 语句并否定该值以模拟 ASC 或 DESC...即:
Now, with a numeric column I would simply use a case statement and negate the value to emulate ASC or DESC... That is:
... ORDER BY CASE @OrderAscOrDesc WHEN 0 THEN [NumericColumn] ELSE -[NumericColumn] END ASC
使用 alpha 列执行此操作的合适方法是什么?
What is an appropriate method for doing this with an alpha column?
我想到了一个聪明的方法,但它似乎非常低效......我可以将我的有序 alpha 列插入一个带有自动编号的临时表中,然后使用上述方法按自动编号排序.
I thought of a clever way but it seems terribly inefficient... I could insert my ordered alpha column into a temp table with an autonumber then sort by the autonumber using the method described above.
编辑 2:
你们如何看待这种方法?
What do you guys think of this approach?
ORDER BY CASE @OrderAscOrDesc WHEN 0 THEN [AlphaColumn] ELSE '' END ASC,
CASE @OrderAscOrDesc WHEN 0 THEN '' ELSE [AlphaColumn] END DESC
我不知道强制对统一列进行排序是否比从排序字符串中导出数字更有效
I don't know if forcing a sort on a uniform column is more efficient than deriving numbers from sorted strings though
推荐答案
一个选项
;WITH cQuery AS
(
SELECT
*,
ROW_NUMBER() OVER (ORDER BY SortColumn) AS RowNum
FROM
MyTable
)
SELECT
*
FROM
cQuery
ORDER BY
RowNum * @Direction --1 = ASC or -1 = DESC
或者恕我直言有点丑的案例
Or CASE which IMHO is a bit uglier
ORDER BY
CASE WHEN 'ASC' THEN SortColumn ELSE '' END ASC,
CASE WHEN 'DESC' THEN SortColumn ELSE '' END DESC
相关文章