存储过程万能分页

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
alter PROCEDURE Pro_AllPageListSelect
@pageIndex INT =1,-- 当前页
@pageSize INT =10,--每页数据
@totalCount INT OUTPUT ,--数据总数 输出参数
@tableName NVARCHAR(100), --表名
@order NVARCHAR(100), --排序字段
@where NVARCHAR(100) --查询条件
AS
BEGIN
SET NOCOUNT ON;
--查询总数据量
--拼接查询总数的sql语句
DECLARE @sqlCount NVARCHAR(2000)='';
DECLARE @allCount INT =0;
SET @sqlCount+=' SELECT @totalCount = COUNT(1) FROM ' +@tableName +' '+ @where;
--执行系统存储过程 可以执行拼接的sql语句
EXEC sp_executesql @sqlCount,N'@totalCount int output',@totalCount OUTput

--拼接调取分页数据的sql
DECLARE @sqlSelect NVARCHAR(2000)='';

SET @sqlSelect ='SELECT TOP ('+CONVERT(NVARCHAR(50), @pageSize)+') * FROM (
SELECT ROW_NUMBER() OVER (ORDER BY '+@order+') AS rowNum, * FROM '+ @tableName +' '+ @where +
') t WHERE t.rowNum> '+CAST( (@pageIndex-1)*@pageSize AS NVARCHAR(50));
--执行sql 1
--EXEC sp_executesql @sqlSelect
--执行sql 2
EXEC ( @sqlSelect)
END
GO

/**
--执行单个sql 语句 参数只需传递拼接的sql语句
DECLARE @sqlCount NVARCHAR(2000)='';
declare @tableName nvarchar(100)='studentnew';
SET @sqlCount+=' SELECT COUNT(1) FROM ' +@tableName ;
EXEC sp_executesql @sqlCount
**/

原文地址:https://www.cnblogs.com/w-pengchao/p/7872769.html