Conditional SQL ORDER BY ASC/DESC for alpha columns

前端 未结 2 1859
南方客
南方客 2020-12-03 11:38

Writing a stored procedure in MS SQL Server 2008 R2, I want to avoid using DSQL...

I would like the sort method (ASC or DESC) to be conditional.

Now, with a

相关标签:
2条回答
  • 2020-12-03 11:50

    This is one of those cases when specific solutions may be preferable preferable to generic ones, especially when we deal with large amounts of data. I would:

    IF @OrderAscOrDesc = 0 THEN BEGIN
      SELECT ...
      FROM  ... 
      ORDER BY [AlphaColumn] ASC
    END ELSE BEGIN
      SELECT ...
      FROM  ... 
      ORDER BY [AlphaColumn] DESC
    END
    

    If you have an index on [AlphaColumn], you might sometimes get a better plan with a more specific query, than with a generic one-size-fits-all one.

    Edit: to facilitate code reuse, you can wrap your select in an inline UDF - it will perform just as well:

    IF @OrderAscOrDesc = 0 THEN BEGIN
      SELECT ...
      FROM  YourInlineUdf(...)
      ORDER BY [AlphaColumn] ASC
    END ELSE BEGIN
      SELECT ...
      FROM  YourInlineUdf(...) 
      ORDER BY [AlphaColumn] DESC
    END
    
    0 讨论(0)
  • 2020-12-03 12:03

    One option

    ;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
    
    0 讨论(0)
提交回复
热议问题