SQL 分页存储
1、实例:存储过程
ALTER PROCEDURE [dbo].[UP_GetRecordByPage2005]
@tblName varchar(255), -- 表名
@fldName varchar(255), -- 主键字段名
@selectField nvarchar(1000),--- 查询字段
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@orderWhere nvarchar(200), -- 设置排序条件
@strWhere nvarchar(1000) = '', -- 查询条件 (注意: 不要加 where)
@IsReCount bit = 0 -- 返回记录总数, 非 0 值则返回
AS
set nocount on
declare @sqlstr nvarchar(4000)
if @IsReCount=1
begin
set @sqlstr=' select count('+@fldName+') as ct from '+@tblName
if @strWhere<>''
set @sqlstr=@sqlstr+' where '+@strWhere
--print @sqlstr
exec(@sqlstr)
end
else
begin
declare @PageLowerBound int --定义此页的底码
declare @PageUpperBound int --定义此页的顶码
set @PageLowerBound=(@PageIndex-1)*@PageSize + 1
set @PageUpperBound=@PageLowerBound+@PageSize - 1
set @sqlstr=' select '+@selectField+' from '+@tblName+' where '+@fldName+' in('
set @sqlstr=@sqlstr+' Select '+@fldName+' FROM ('
set @sqlstr=@sqlstr+' select '+@fldName+',ROW_NUMBER() Over(order by '+@orderWhere+') as rowId from '
set @sqlstr=@sqlstr+' '+@tblName+' with(nolock) '
if @strWhere<>''
set @sqlstr=@sqlstr+' where '+@strWhere
set @sqlstr=@sqlstr+' )'
set @sqlstr=@sqlstr+' as t where rowId between '+cast(@PageLowerBound as nvarchar(20))+' and '+cast(@PageUpperBound as nvarchar(20))
set @sqlstr=@sqlstr+' ) order by '+@orderWhere
print @sqlstr
exec(@sqlstr)
end