今天花了两个小时,写了两种分页的算法。
--not in删选法,这种方法查询某个表中前面的数据效率高
create procedure Page_proc
(
@pageSize int, --页数,
@pageIndex int,--页码
@tableName varchar(50),--表名
@mast varchar(50)--表的主键名
)
as
begin
declare @arg int
set @arg=@pageSize*(@pageIndex-1)
--使用动态Sql
declare @strSql varchar(1000)
set @strSql='select top('+cast(@pageSize as varchar(20))+') * from '+@tableName
+' where '+@mast+' not in(select top('+cast(@arg as varchar(20))+') '+@mast+' from '+@tableName+')'
print @strSql
exec(@strSql)
end
--正序倒序法,这种方法查询某个表中后面的数据效率高
create proc FenYe
@tableName varchar(50),--表名
@mast varchar(50),--表的主键名
@pageIndex int,--页码
@pageCount int--页数
as
begin
--求出表的总行数,由于是动态Sql给@RowCount赋值,所以需要用到sp_executesql
declare @RowCount int
declare @countSql nvarchar(200)
set @countSql='select @innerCount=count(*) from '+@tableName
exec sp_executesql @countSql,N'@innerCount int output',@RowCount output
--print @RowCount
--求出子查询要查的行数
declare @Count int
set @Count=@RowCount-(@pageIndex-1)*@pageCount
--如果查询条件不符合则结束此存储过程
if(@Count<0)
return ;
--使用动态Sql
declare @strSql varchar(1000)
set @strSql='select top '+cast(@pageCount as varchar(20))+' * from '+'(select top '+
cast(@Count as varchar(20))+' * from '+cast(@tableName as varchar(50))+' order by '
+cast(@mast as varchar(50))+' desc) as temp order by '+cast(@mast as varchar(50))
print @strSql
exec(@strSql)
end
@tableName varchar(50),--表名
@mast varchar(50),--表的主键名
@pageIndex int,--页码
@pageCount int--页数
as
begin
--求出表的总行数,由于是动态Sql给@RowCount赋值,所以需要用到sp_executesql
declare @RowCount int
declare @countSql nvarchar(200)
set @countSql='select @innerCount=count(*) from '+@tableName
exec sp_executesql @countSql,N'@innerCount int output',@RowCount output
--print @RowCount
--求出子查询要查的行数
declare @Count int
set @Count=@RowCount-(@pageIndex-1)*@pageCount
--如果查询条件不符合则结束此存储过程
if(@Count<0)
return ;
--使用动态Sql
declare @strSql varchar(1000)
set @strSql='select top '+cast(@pageCount as varchar(20))+' * from '+'(select top '+
cast(@Count as varchar(20))+' * from '+cast(@tableName as varchar(50))+' order by '
+cast(@mast as varchar(50))+' desc) as temp order by '+cast(@mast as varchar(50))
print @strSql
exec(@strSql)
end
这两种是最常用的,第一次发技术随笔,不足之处请大家了解。
使用正序倒叙法查询表前面的数据成功例子:
select * from (select top 10 * from (select top 12 * from A0002 order by ID asc) as temp order by ID desc) as tt order by ID
select top 10 * from (select top 12 * from A0002 order by ID asc) as temp order by ID asc
使用正序倒叙法查询表前面的数据失败例子:
select top 10 * from (select top 12 * from A0002 order by ID asc) as temp order by ID asc