Suppose I use a Northwind database, and I would like to run a query through a stored procedure that contains, among other parameters, the following:
@Offset to indicate where pagination begins,@Limit to indicate page size,@SortColumn to indicate the column used for sorting,@SortDirection to indicate sorting by ascendant or descendants.
The idea is to do pagination in the database, since the result set contains thousands of rows, so caching is not an option (and using VIEWSTATE is not even considered, IMO, sucks).
As you know, SQL Server 2005 provides the ROW_NUMBER function, which returns the row number in a section of a result set, starting at 1 for the first row in each section.
We need to sort by each returned column (five in this example), and dynamic SQL is not an option, so we have two options: using a large number of IF ... ELSE ... and having 10 queries that damn it support , or the request is as follows:
WITH PaginatedOrders AS ( SELECT CASE (@SortColumn + ':' + @SortDirection) WHEN 'OrderID:A' THEN ROW_NUMBER() OVER (ORDER BY Orders.OrderID ASC) WHEN 'OrderID:D' THEN ROW_NUMBER() OVER (ORDER BY Orders.OrderID DESC) WHEN 'CustomerID:A' THEN ROW_NUMBER() OVER (ORDER BY Orders.CustomerID ASC) WHEN 'CustomerID:D' THEN ROW_NUMBER() OVER (ORDER BY Orders.CustomerID DESC) WHEN 'EmployeeID:A' THEN ROW_NUMBER() OVER (ORDER BY Orders.EmployeeID ASC) WHEN 'EmployeeID:D' THEN ROW_NUMBER() OVER (ORDER BY Orders.EmployeeID DESC) WHEN 'OrderDate:A' THEN ROW_NUMBER() OVER (ORDER BY Orders.OrderDate ASC) WHEN 'OrderDate:D' THEN ROW_NUMBER() OVER (ORDER BY Orders.OrderDate DESC) WHEN 'ShippedDate:A' THEN ROW_NUMBER() OVER (ORDER BY Orders.OrderID ASC) WHEN 'ShippedDate:D' THEN ROW_NUMBER() OVER (ORDER BY Orders.OrderID DESC) END AS RowNumber, OrderID, CustomerID, EmployeeID, OrderDate, ShippedDate FROM Orders
I tried the request several times, with different arguments, and its performance is actually quite good, but it still looks like it could be optimized in some other way.
Is there something wrong with this question, or will you do it like that? Do you suggest a different approach?
sql-server-2005 pagination
Leandro Lรณpez Oct 23 '08 at 14:56 2008-10-23 14:56
source share