创建存贮过程:
Create PROCEDURE [dbo].[UP_GetRecordByPage]
@tblName varchar(255), -- 表名
@fldName varchar(1000) = '*', -- 需要返回的列,默认*
@strOrder varchar(255)='', -- 排序的字段名,必填。后面跟着排序方式,如UserName Desc ,多个排序字段用逗号分开,
@PageSize int = 10, -- 页尺寸,默认10
@PageIndex int = 1, -- 页码,默认1
@strWhere varchar(1500) = '', -- 查询条件 (注意: 不要加 where)
@TotalCount int output --返回记录总数
AS
declare @strSQL varchar(5000)
declare @totalSql nvarchar(4000)
if @strWhere !=''
set @strWhere=' where '+@strWhere
--总记录数
set @totalSql='SELECT @TotalCount=COUNT(*) FROM '+@tblName+' '+@strWhere
exec sp_executesql @totalSql,N'@TotalCount int OUTPUT',@TotalCount OUTPUT
set @strSQL=
'SELECT * FROM ('+
'SELECT ROW_NUMBER() OVER (ORDER BY '+@strOrder+') AS pos,'+@fldName+' '+
'FROM '+@tblName+' '+@strWhere+
') AS sp WHERE pos BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND '+str(@PageIndex*@PageSize)
exec (@strSQL)
备注:记录总数是以output参数返回
使用测试:
declare @count int
exec UP_GetRecordByPage
'UserInfo','*','UserName desc',10,1,'',@count output ;
print @count;