支持:多表连接查询、Group by分组查询等。(多表连接查询时请指定字段,不要用SELECT *)
返回为一结果集,有一个输出参数为记录总数,配合AspNetPager控件使用绝配。
转载请注明出处,欢迎讨论Pk。
CREATE PROCEDURE web_pager (
@rowsTotal INT OUTPUT, --输出记录总数
@tableName VARCHAR(800), --表名
@fieldName VARCHAR(800), --查询字段
@keyName VARCHAR(200), --索引字段
@pageSize INT, --每页记录数
@pageNow INT, --当前页
@stringOrder VARCHAR(200), --排序条件
@stringWhere VARCHAR(800) --WHERE条件
)
AS
BEGIN
DECLARE @beginRow INT
DECLARE @endRow INT
DECLARE @tempLimit VARCHAR(200)
DECLARE @tempCount NVARCHAR(1000)
DECLARE @tempMain VARCHAR(1000)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
SET @beginRow = (@pageNow - 1) * @pageSize + 1
SET @endRow = @pageNow * @pageSize
SET @tempLimit = 'rows BETWEEN ' + CAST(@beginRow AS VARCHAR) +' AND '+CAST(@endRow AS VARCHAR)
--输出参数为总记录数
SET @tempCount = 'SELECT @rowsTotal = COUNT(*) FROM (SELECT '+@keyName+' FROM '+@tableName+' WHERE '+@stringWhere+') AS my_temp'
EXECUTE sp_executesql @tempCount,N'@rowsTotal INT OUTPUT',@rowsTotal OUTPUT
--主查询返回结果集
SET @tempMain = 'SELECT * FROM (SELECT ROW_NUMBER() OVER ('+@stringOrder+') AS rows ,'+@fieldName+' FROM '+@tableName+' WHERE '+@stringWhere+') AS main_temp WHERE '+@tempLimit
EXECUTE (@tempMain)
END