分页存储过程
- Create PROCEDURE [dbo].[GetRecordWithPage]
- @fieldsType nvarchar(1000), --字段列表(带类型),用于@t表变量的字段声明,如:PhotoID int,UserID int,PhotoTitle nvarchar(50)
- @fieldsList nvarchar(500), --字段列表(不带类型),用于分页部分读取@t表变量的字段,也可使用*代替,但性能会下降,如:PhotoID ,UserID ,PhotoTitle
- @selectSrting nvarchar(2000), --向@t表变量中读取记录的Select语句
- @resultOrderBy nvarchar(200), --对分页结果进行排序的字段,如:升序'PhotoID ASC'、降序'PhotoID DESC',注意:如果是降序的话要在selectSrting和此处都加DESC
- @pageSize INT, --页尺寸,0表示返回所有行
- @currentPage INT, --当前页,首页为1
- @RecordCount INT OUTPUT --非0值则返回记录总数
- AS
- BEGIN
- DECLARE @strSql varchar(4000)
- declare @sql nvarchar(1000)
- SET @strSql = 'DECLARE @t TABLE(' +@fieldsType+ ');'
- SET @strSql = @strSql + 'INSERT INTO @t '+@selectSrting+ ';'
- set @sql = @strSql + 'select @aa=count(*) from @t;'
- exec sp_executesql @sql,N'@aa int output',@RecordCount OUTPUT;
- IF @pageSize=0
- SET @strSql=@strSql+'SELECT '+@fieldsList+' FROM @t;'
- ELSE
- IF @currentPage=1
- SET @strSql=@strSql+'select TOP('+STR(@pageSize)+')'+@fieldsList+' FROM @t;'
- ELSE
- BEGIN
- SET @strSql =@strSql+'SELECT TOP('+Str(@pageSize)+')'+ @fieldsList+'FROM (SELECT TOP('+Str(@pageSize * @currentPage)+')'+@fieldsList+' , ROW_NUMBER() OVER (ORDER BY '+@resultOrderBy+')'
- SET @strSql =@strSql+' AS RowNumber FROM @t'
- SET @strSql =@strSql+') AS r WHERE r.RowNumber >' + Str(@pageSize * (@currentPage - 1))+';'
- END
- EXEC(@strSql)
- END
分页函数:
- Create Function [dbo].[F_ConformationPage]
- (
- @pageNum int, --页码
- @pageSize int,--页面大小
- @orderExpression nvarchar(50),--排序表达式如:'ID DESC'
- @oldSql nvarchar(max) --待分页的sql语句
- )
- RETURNS Nvarchar(max) --待分页sql语句
- AS
- begin
- declare @newSql Nvarchar(max)
- set @newSql=''
- declare @beginPage as nvarchar(100) --开始数字
- set @beginPage=(@pageNum*@pageSize)-(@pageSize-1)
- declare @endPage nvarchar(100)
- set @endPage=@beginPage+@pageSize-1
- set @newSql='select * from (
- SELECT Row_Number( ) over( ORDER BY '+ @orderExpression +') as rowNum,* from ('+@oldSql+') as aa) as yy
- where rowNum BETWEEN '+ @beginPage+' and '+@endPage+' order by '+ @orderExpression
- return @newSql
- end