代码改变世界

简单的SQL分页法

2008-04-02 20:36  Koy  阅读(325)  评论(0编辑  收藏  举报
简单的SQL分页法

select top 10 * from User u1
    where u1.Id not in (
        select top 10*@page u2.Id from User u2 order by u2.Id asc
    )
order by u1.Id

其中 top 10 为我们需要分页的项目数, @page 为页数;如:我们现在需要 1-10条的记录 page=0,需要11-20的记录 page=1
=====================================================================

DECLARE @page int
DECLARE @size int
SET @size = 10
SET @page = 1

select TOP(@size) * from Users u1
    where u1.UserId not in (
        select TOP(@size*@page) u2.UserId from Users u2 order by UserId asc
    )
    ORDER BY u1.UserID asc


=====================================================================
附上另一方法:
WITH OrderedOrders AS
(SELECT *,
ROW_NUMBER() OVER (order by [id])as RowNumber  --id是用来排序的列
FROM table_info ) --table_info是表名
SELECT *
FROM OrderedOrders
WHERE RowNumber between 50 and 60;

在windows server 2003, sql server 2005 CTP,P4 2.66GHZ,1GB 内存下测试,执行时间0秒 ,表中数据量230万