通过SQL语句分页的方法--MS SQL/ Oralcle

来源:互联网 发布:python密码字典生成器 编辑:程序博客网 时间:2024/06/14 22:06

MS SQL :

1:临时表”方法:即在存储过程中建立一个临时表,该临时表包含一个序号字段(1,2,3,....)以及表的主键(其他能够唯一确定一行记录的字段也是可以的)字段。存储过程可能如下:
CREATE Procedure GetAllArticles_Paged
(
     @PageIndex int,
     @PageSize int,
     @TotalRecords out int,
     @TotalPages out int
)
AS

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #tmp
(
     RecNo int IDENTITY (1, 1) NOT NULL,
     ArticleID int
)

INSERT INTO #tmp
     SELECT [ID]
     FROM Articles
     ORDER BY PubTime DESC

SELECT A.*
FROM Articles A (nolock), #tmp T
WHERE A.ID = T.ArticleID AND
     T.RecNo > @PageLowerBound AND
     T.RecNo < @PageUpperBound
ORDER BY T.RecNo

GO

2:“掐头去尾”拼凑SQL 语句:用两次 TOP 命令取得我们所要的分页数据,例如
SELECT * FROM
     (
     SELECT TOP(PageSize) * FROM
     (
          SELECT TOP (PageSize * PageIndex) *
          FROM Articles
          ORDER BY PubTime DESC
     )
     ORDER BY PubTime ASC
)
ORDER BY PubTime DESC

 

 

Oracle 数据库

oracle提供了 rownum 这个隐式游标。

rownum 是记录序号(1,2,3...)

SELECT * FROM
     (
     SELECT A.*, rownum r
     FROM
          (
          SELECT *
          FROM Articles
          ORDER BY PubTime DESC
          ) A
     WHERE rownum <= PageUpperBound
     ) B
WHERE r > PageLowerBound;

 

原创粉丝点击