我需要使用数据库端分页,如果一个表有10,000条记录,那么我必须首先获取100条记录然后再进行100条记录。我正在使用SQL Server 2005请为此提供存储过程代码。
答案 0 :(得分:2)
您应该查看自SQL Server 2005以来可用的ROW_NUMBER()函数。
事实证明,这是执行服务器端分页的最有效方式(在我的情况下)。
示例:
SELECT *
FROM (
SELECT col1, col2, col3,
ROW_NUMBER() OVER(ORDER BY col1 ASC) AS rownbr
FROM table
WHERE col2 = 'something'
) AS Query
WHERE rownbr BETWEEN 1 AND 10
ORDER BY rownbr
您可以在OVER()语句中设置要排序的列,并在外部WHERE语句中设置要检索的第一行和最后一行。
答案 1 :(得分:2)
DECLARE @PageSize INT,
@PageNumber INT,
@FirstRow INT,
@LastRow INT
SELECT @PageSize = 20,
@PageNumber = 1
SELECT @FirstRow = ( @PageNumber - 1) * @PageSize + 1,
@LastRow = (@PageNumber - 1) * @PageSize + @PageSize ;
WITH Members AS
(
SELECT Col1,Col2,Col3,
ROW_NUMBER() OVER (ORDER BY Col1 DESC) AS RowNumber
FROM Table
)
SELECT Col1,Col2,..,..,..,
FROM Members
WHERE RowNumber BETWEEN @FirstRow AND @LastRow
ORDER BY Col1 ASC;
答案 2 :(得分:1)
如果您实际上尝试在页面编号的页面上进行分页,那么您可以执行以下操作:
Create Procedure GetPagedStuff( @PageNumber int, @PageSize int )
As
;With RankedRows As
(
Select ...
, Row_Number() Over ( Order By SomeColumn ) As Num
, Count( NonNullColumn ) Over() As TotalRows
From MyTable
)
Select ...
From RankedRows
Where Num > (@PageNumber - 1) * @PageSize
And Num <= @PageNumber * @PageSize
Return
-- example call
Exec GetPagedStuff @PageNumber = 1, @PageSize = 100
答案 3 :(得分:1)
根据杰森和托马斯的建议,ROW_NUMBER()函数是你最好的选择。但是,如果满足WHERE子句的记录数量非常高,您可能只想检索主键,然后再次使用同一个表连接子集以获取其他列。
例如:
SELECT e.col1, e.col2, e.col3
FROM Table1 e
JOIN
(SELECT ID, rownum= ROW_NUMBER()
FROM Table1
WHERE col1 = @filterParam
ORDER BY LastName)
f ON f.ID = e.ID
WHERE f.rownum BETWEEN 100 AND 150