一个基于ROW_NUMBER()的通用分页存储过程代码

前端之家收集整理的这篇文章主要介绍了一个基于ROW_NUMBER()的通用分页存储过程代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

建立好如下的存储过程,以后要分页,直接调用改存储过程就可以了。
注意:数据量大、性能要求高的,请个性化处理。
<div class="codetitle"><a style="CURSOR: pointer" data="86060" class="copybut" id="copybut86060" onclick="doCopy('code86060')"> 代码如下:

<div class="codebody" id="code86060">
ALTER PROCEDURE [dbo].[COMMON_PROCEDURE_SelectWithPage]
@sql VARCHAR(5000),
@CurrentPageNo INT,
@PageSize INT,
@TotalNum INT OUTPUT
AS
SET NOCOUNT ON
DECLARE @sqlCmd VARCHAR(5000)
------------------------------------------ --查询数据
SET @sqlCmd = 'SELECT FROM (' + @sql + ') A WHERE RowIndex BETWEEN ' + CONVERT(VARCHAR,(@CurrentPageNo-1) @PageSize + 1) + ' AND ' + CONVERT(VARCHAR,@CurrentPageNo @PageSize)
EXEC(@sqlCmd) PRINT (@sqlCmd)
------------------------------------------ --求记录总数
IF @TotalNum = -1
BEGIN
CREATE TABLE #Temp1(num INT)
INSERT INTO #Temp1
EXEC('SELECT count(
) FROM (' + @sql + ') A')
SELECT @TotalNum=(SELECT FROM #Temp1)
DROP TABLE #Temp1
END 用法很简单,但必须在传入的sql中使用ROW_NUMBER() OVER(...) AS RowIndex :
DECLARE @sql VARCHAR(5000)
DECLARE @CurrentPageNo INT
DECLARE @PageSize INT
DECLARE @TotalNum INT SET @CurrentPageNo = 100
SET @PageSize = 10
SET @TotalNum = -1
SET @sql = ' SELECT
,ROW_NUMBER() OVER (ORDER BY 排序字段) AS RowIndex FROM 表名 A WITH (NOLOCK) ' EXEC [dbo].[COMMON_PROCEDURE_SelectWithPage] @sql,@CurrentPageNo,@PageSize,@TotalNum OUTPUT SELECT @TotalNum

原文链接:https://www.f2er.com/mssql/64055.html

猜你在找的MsSQL相关文章