SQL Server的分页可以有几种方式实现,例如最简单的:
1、select top 20 * from table where id not in(select top 200 id from table where ?)即取20条记录,并且这些记录是不在当前页的之前的那些页的记录中。这个方式比较简单,但破坏SQL的可读性,并且当你的该SQL语句有很多的过滤条件时,显得特别恶心了,例如 select top pagesize from table where id not in(select top pagesize * (curPage - 1) id from table where create_date > 'aaaa' and create_date < 'aaaaa' and....) and create_date > 'aaaa' and create_date < 'aaaaa' and.......。如果你的程序本身已经已经有了大量的JDBC操作sql语句,那现在突然让你加一个分页的功能,。
2、用后台SQL SERVER的存储过程来实现分页:
CREATE procedure pageProcedure
@sqlstr nvarchar(4000), --查询字符串
@currentpage int, --第N页
@pagesize int, --每页行数
@out_row_count int output,--输出总行数
@out_page_count int output--输出总页数
as
set nocount on
declare @P1 int, --P1是游标的id
@rowcount int
exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output
--select ceiling(1.0*@rowcount/@pagesize) as 总页数,@rowcount as 总行数,@currentpage as 当前页
set @out_row_count = @rowcount
set @out_page_count = ceiling(1.0*@rowcount/@pagesize)
set @currentpage=(@currentpage-1)*@pagesize+1
exec sp_cursorfetch @P1,16,@currentpage,@pagesize
exec sp_cursorclose @P1
set nocount off
GO
调用
declare @row_count int
declare @page_count int
exec pageProcedure 'select * from employees', 1, 200, @row_count, @page_count