Paginated query using sorting on different columns using ROW_NUMBER() OVER () in SQL Server 2005

后端 未结 1 1931
深忆病人
深忆病人 2020-12-24 03:51

Let\'s suppose I\'m using the Northwind database and I would like to run a query via a stored procedure that contains, among other parameters, the following:

  • <
相关标签:
1条回答
  • 2020-12-24 04:23

    Simple:

    SELECT
      OrderID, CustomerID, EmployeeID, OrderDate, ShippedDate,
      @Offset, @Limit, @SortColumn, @SortDirection
    FROM
      Orders
    WHERE
      ROW_NUMBER() OVER 
      (
        ORDER BY
          /* same expression as in the ORDER BY of the whole query */
      ) BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize 
      /* AND more conditions ... */
    ORDER BY
      CASE WHEN @SortDirection = 'A' THEN
        CASE @SortColumn 
          WHEN 'OrderID'    THEN OrderID
          WHEN 'CustomerID' THEN CustomerID
          /* more... */
        END
      END,
      CASE WHEN @SortDirection = 'D' THEN
        CASE @SortColumn 
          WHEN 'OrderID'    THEN OrderID
          WHEN 'CustomerID' THEN CustomerID
          /* more... */
        END 
      END DESC
    

    This will sort on NULL (DESC) if ASC order is selected, or vice versa.

    Let the ROW_NUMBER() function work over the same ORDER BY expression.

    0 讨论(0)
提交回复
热议问题