分页存储过程
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
CREATE PROCEDURE [dbo].[GetTreeDetails]
@start int ,--数据页码
@limit int ,--每页显示数据条数
@totalCount int OUT ,--数据总条数
@flag int ,--数据总页数
@where nvarchar(200)
AS
declare @sql nvarchar(4000)
declare @pageCount int
if @flag=0
begin
select @totalCount=count(*) from treeDetails
set @pageCount=CEILING (@totalCount * 1.0 / @limit)
if @start=0
set @sql=N'select top '+STR(@limit)+' * from treeDetails'
else if @start=@pageCount-1
set @sql=N'select top '+STR(@limit)+' * from treeDetails where id not in (select top '+str(@start*@limit)+' id from treeDetails order by id) order by id'
else
set @sql=N'select top '+STR(@limit)+' * from treeDetails where id not in (select top '+str(@start*@limit)+' id from treeDetails order by id) order by id'
end
else
begin
declare @sql1 nvarchar(4000)
declare @total int
set @sql1=N'select @totalCount =count(*) from treeDetails where 1=1 ' + cast(@where as nvarchar(200))
Exec sp_executesql @sql1,N'@totalCount int=0 OUTPUT',@totalCount=@totalCount OUTPUT
set @pageCount=CEILING(@totalCount * 1.0 / @limit)
if @start=0
set @sql=N'select top ' +STR(@limit)+' * from treeDetails where 1=1 ' + cast(@where as nvarchar(200))
else if @start=@pageCount-1
set @sql=N'select * from treeDetails where id not in (select top '+str(@start*@limit)+' id from treeDetails where 1=1 '+cast(@where as nvarchar(200)) +') ' + cast(@where as nvarchar(200))
else
set @sql=N'select top '+STR(@limit)+' * from treeDetails where id not in (select top '+str(@start*@limit)+' id from treeDetails where 1=1 '+ cast(@where as nvarchar(200)) +') '+ cast(@where as nvarchar(200))
end
Exec sp_executesql @sql
方法1:
适用于 SQL Server 2000/2005
FROM table1
WHERE id NOT IN
(
SELECT TOP 页大小*(页数-1) id FROM table1 ORDER BY id
)
ORDER BY id
方法2:
适用于 SQL Server 2000/2005
FROM table1
WHERE id >
(
SELECT ISNULL(MAX(id),0)
FROM
(
SELECT TOP 页大小*(页数-1) id FROM table1 ORDER BY id
) A
)
ORDER BY id
方法3:
适用于 SQL Server 2005
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1
) A
WHERE RowNumber > 页大小*(页数-1)
说明,页大小:每页的行数;页数:第几页。使用时,请把“页大小”和“页大小*(页数-1)”替换成数字。
其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。
通过SQL 查询分析器,显示比较:我的结论是:
分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句
分页方案一:(利用Not In和SELECT TOP分页) 效率次之,需要拼接SQL语句
分页方案三:(利用SQL的游标存储过程分页) 效率最差,但是最为通用