一個基於ROW_NUMBER()的通用分頁存儲進程代碼。本站提示廣大學習愛好者:(一個基於ROW_NUMBER()的通用分頁存儲進程代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是一個基於ROW_NUMBER()的通用分頁存儲進程代碼正文
樹立好以下的存儲進程,今後要分頁,直接挪用改存儲進程便可以了。
留意:數據量年夜、機能請求高的,請特性化處置。
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