SQL Server 2005 通用分页存储过程
来源:程序员人生 发布时间:2014-03-04 07:06:49 阅读次数:3246次
通过SQLServer 2005之后新加入的ROW_NUMBER()函数进行分页:
set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgo-- =============================================-- Author: <Author,,Name>-- Description: <通用分页存储过程>-- =============================================Create PROCEDURE [dbo].[ClientNewsPager] @talbeName varchar(255)='', -- 表名 @getFields varchar(1000)='*', -- 需要返回的列 @orderBy varchar(255)='', -- 排序的字段名 @PageSize int=15, -- 页尺寸 @PageIndex int=1, -- 页码,从1开始 @doCount bit=0, -- 返回记录总数, 非 0 值则返回 @whereStr varchar(1500)='' -- 查询条件 (注意: 不要加 where)ASBEGIN declare @rowResult intBegin Tran declare @strSQL varchar(5000) declare @startRowIndex int declare @maximumRows int set @startRowIndex = (@PageIndex - 1) * @PageSize set @maximumRows = @startRowIndex + @PageSize if(@doCount!=0) begin if @whereStr !='' set @strSQL = 'select id from ' + @talbeName + ' where '+ @whereStr else set @strSQL = 'select id from ' + @talbeName end else begin if(@whereStr!='') begin set @strSQL = 'SELECT ' + @getFields + ' FROM (SELECT ROW_NUMBER() OVER (ORDER BY ' + @orderBy + ') AS RowsNum,' + @getFields + ' FROM ' + @talbeName + ' where ' + @whereStr + ') AS TMP WHERE (RowsNum > ' + str(@startRowIndex) + ' AND RowsNum <= ' + str(@maximumRows) + ')' end else begin set @strSQL = 'SELECT ' + @getFields + ' FROM (SELECT ROW_NUMBER() OVER (ORDER BY ' + @orderBy + ') AS RowsNum,' + @getFields + ' FROM ' + @talbeName + ') AS TMP WHERE (RowsNum > ' + str(@startRowIndex) + ' AND RowsNum <= ' + str(@maximumRows) + ')' end end exec(@strSQL) Set @rowResult = @@ROWCOUNTIf @@Error <> 0 Begin RollBack Tran Return -1 End Else Begin Commit Tran Return @rowResult EndEND