CREATE PROCEDURE CD_Pager (
@recordTotal INT OUTPUT, --默认为零输出记录总数
@viewName VARCHAR(800), --表名
@fieldName VARCHAR(800) = '*', --查询字段
@pageSize INT = 20, --每页记录数
@pageNo INT =1, --当前页
@orderString VARCHAR(200), --排序条件
@whereString VARCHAR(800) = '1=1' --WHERE条件
)
AS
BEGIN
DECLARE @beginRow INT
DECLARE @endRow INT
DECLARE @tempLimit VARCHAR(200)
DECLARE @tempCount NVARCHAR(1000)
DECLARE @tempMain VARCHAR(1000)
SET @beginRow = (@pageNo - 1) * @pageSize + 1
SET @endRow = @pageNo * @pageSize
SET @tempLimit = 'rows BETWEEN ' + CAST(@beginRow AS VARCHAR) +' AND '+CAST(@endRow AS VARCHAR)
IF @recordTotal<>0
BEGIN
--输出参数为总记录数
SET @tempCount = 'SELECT @recordTotal = COUNT(1) FROM '+@viewName+' WHERE '+@whereString
EXECUTE sp_executesql @tempCount,N'@recordTotal INT OUTPUT',@recordTotal OUTPUT
END
--主查询返回结果集
SET @tempMain = 'SELECT * FROM (SELECT ROW_NUMBER() OVER ('+@orderString+') AS rows ,'+@fieldName+' FROM '+@viewName+' WHERE '+@whereString+') AS main_temp WHERE '+@tempLimit
--PRINT @tempMain
EXECUTE (@tempMain)
END