通用分页存储过程,干货无污染

Posted 追逐时光者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通用分页存储过程,干货无污染相关的知识,希望对你有一定的参考价值。

/*********************************************************************************
*      Function:  WEB_PageView2													 *
*      Description:                                                              *
*             Sql2005分页存储过程												 *
*      Finish DateTime:                                                          *
*             2009/1/3															 *
*	   Example:																	 *
*	          WEB_PageView @Tablename = ‘Table1‘, @Returnfields = ‘*‘,           *
*			  @PageSize = 2, @PageIndex = 1, @Where = ‘‘,					     *
*			  @OrderBy=N‘ORDER BY id desc‘										 *           
*********************************************************************************/

IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N‘[dbo].[WEB_PageView]‘) and OBJECTPROPERTY(ID, N‘IsProcedure‘) = 1)
DROP PROCEDURE [dbo].[WEB_PageView]
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_NULLS ON 
GO


CREATE PROCEDURE dbo.WEB_PageView
	@TableName		NVARCHAR(200),			-- 表名
	@ReturnFields	NVARCHAR(1000) = ‘*‘,	-- 查询列数
	@PageSize		INT = 10,				-- 每页数目
	@PageIndex		INT = 1,				-- 当前页码
	@Where			NVARCHAR(1000) = ‘‘,	-- 查询条件
	@OrderBy		NVARCHAR(1000),			-- 排序字段
	@PageCount		INT OUTPUT,				-- 页码总数
	@RecordCount	INT OUTPUT	        	-- 记录总数
WITH ENCRYPTION AS

--设置属性
SET NOCOUNT ON

-- 变量定义
DECLARE @TotalRecord INT
DECLARE @TotalPage INT
DECLARE @CurrentPageSize INT
DECLARE @TotalRecordForPageIndex INT

BEGIN
	IF @Where IS NULL SET @Where=N‘‘
	
	-- 记录总数
	DECLARE @countSql NVARCHAR(4000)  
	
	IF @RecordCount IS NULL
	BEGIN
		SET @countSql=‘SELECT @TotalRecord=Count(*) From ‘[email protected]+‘ ‘[email protected]
		EXECUTE sp_executesql @countSql,N‘@TotalRecord int out‘,@TotalRecord OUT
	END
	ELSE
	BEGIN
		SET @[email protected]
	END		
	
	SET @[email protected]
	SET @TotalPage=(@TotalRecord-1)/@PageSize+1	
	SET @CurrentPageSize=(@PageIndex-1)*@PageSize

	-- 返回总页数和总记录数
	SET @[email protected]
	SET @[email protected]
		
	-- 返回记录
	SET @[email protected]*@PageSize
	
	EXEC	(‘SELECT *
			FROM (SELECT TOP ‘[email protected]+‘ ‘[email protected]+‘, ROW_NUMBER() OVER (‘[email protected]+‘) AS PageView_RowNo
			FROM ‘[email protected]+ ‘ ‘ + @Where +‘ ) AS TempPageViewTable
			WHERE TempPageViewTable.PageView_RowNo > 
			‘[email protected])
	
END
RETURN 0
GO
			

  

以上是关于通用分页存储过程,干货无污染的主要内容,如果未能解决你的问题,请参考以下文章

三大数据库下的存储过程实现通用分页

通用分页存储过程

markdown 通用分页存储过程

SQL SERVER 通用分页存储过程

通用分页存储过程

SQL存储过程分页(通用的拼接SQL语句思路实现)