search
HomeDatabaseMysql TutorialMSSQL分页存储过程

MSSQL分页存储过程

Jun 07, 2016 pm 02:57 PM
mssqlPaginationstorageprocess

Version1.0.52014.07.15更新 本存储过程是本人查找对比网络上常用的分页存储过程后改写的分页存储过程,拥有较高效率,但不保证效率最高。 本存储过程是在MSSQL2012上编写,不保证兼容所有版本MSSQL(已知MSSQL2005需要修改少量代码)。不兼容其他数据库。 本

Version 1.0.5 2014.07.15更新
本存储过程是本人查找对比网络上常用的分页存储过程后改写的分页存储过程,拥有较高效率,但不保证效率最高。
本存储过程是在MSSQL2012上编写,不保证兼容所有版本MSSQL(已知MSSQL2005需要修改少量代码)。不兼容其他数据库。
本分页存储过程仅支持常用SQL语句。
若发现问题,请联系ttio4116@live.com或到我的个人博客http://blog.ttionya.com留言,共同进步!!

一些注意事项见文件内的README
?SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
README
Version 1.0.5
本存储过程是本人查找对比网络上常用的分页存储过程后改写的分页存储过程,拥有较高效率,但不保证效率最高。
本存储过程是在MSSQL2012上编写,不保证兼容所有版本MSSQL(已知MSSQL2005需要修改少量代码)。不兼容其他数据库。
本分页存储过程仅支持常用SQL语句。
若发现问题,请联系ttio4116@live.com,共同进步!!

版本更新:
Version 1.0.1:修复了查询第一页数据时会采用错误的SQL语句的BUG
Version 1.0.2:更新了部分参数的解释
Version 1.0.3:修复了多表查询时由于表名错误导致的出错
Version 1.0.4:去除了部分不需要的条件判断语句
Version 1.0.5:修复了第一页时GROUP BY的错误,现在可以在@FldName里面加入COUNT()、MAX()等(不限于此)聚合函数

注意:1.HAVING语句需要与GROUP BY语句配合使用,格式为:GROUP BY XXX HAVING XXX。
      2.@FldSort需要给需要排序的字段设置ASC或者DESC。
      3.@strOrder为排序&聚合参数,排序时在没有设置@FldSort时起作用(默认正序排列);聚合时为了计算总条数,若该参数为空时则取@FldSort的第一个字段。
	  4.建议@strOrder设置为主键,就算不是主键也不要包含NULL,否则会发生不可预料的结果。若该参数为空,请务必使@FldSort的第一个字段不含NULL。
*/
CREATE PROCEDURE [dbo].[MyPageRead]
(
@TblName nvarchar(3000)     --连接的表名,即FROM后面的内容
,@FldName nvarchar(3000)='*'     --要查询的字段名称,默认为全部
,@FldSort nvarchar(3000)=NULL     --排序字段,不需要ORDER BY,排序自行设置,请加入ASC或者DESC
,@strCondition nvarchar(3000)=NULL     --要查询的语句,不需要WHERE,前面不需要跟AND或者OR,但是不会影响计算
,@strGroup nvarchar(3000)=NULL     --要聚合的语句,不需要GROUP BY
,@strHaving nvarchar(3000)=NULL     --HAVING语句,不需要HAVING
,@Dist bit=0     --是否去除重复数据,0不去除/1去除
,@strOrder nvarchar(1000)=NULL     --一个排序字段,当@FldSort为空时必须指定。而且该字段用于计算总条数,该字段为空时选取@FldSort的第一个字段
,@OnlyCounts bit=0     --是否只返回总条数而不进行分页

,@PageSize int=10     --每页要显示的数量
,@Page int=1     --要显示那一页的数据

,@Counts int=1 output     --返回总条数
,@PageCounts int=1 output     --返回总页数
)
AS
SET NOCOUNT ON     --不返回计数
--定义变量
DECLARE @tmpFldSort nvarchar(3000)     --构成的ORDER BY语句存放处
DECLARE @tmpstrCondition nvarchar(3000)     --WHERE语句存放处
DECLARE @tmpstrGroup nvarchar(3000)     --GROUP BY语句存放处
DECLARE @tmpstrfirst nvarchar(3000)     --1.开头存放处,控制Dist
DECLARE @tmpstrfirstCount nvarchar(3000)     --2.开头存放处,控制Dist

/*计算时间*/
DECLARE @StartTime datetime
SET @StartTime=GETDATE()


IF (@FldSort IS NULL OR @FldSort='') AND (@strOrder IS NULL OR @strOrder='')
	RETURN
--必须有一个有值,如果有问题,直接跳出

IF @FldSort IS NULL OR @FldSort=''
	SET @tmpFldSort=@strOrder+' ASC '
ELSE
	SET @tmpFldSort=@FldSort
--以上为设置ORDER BY语句

IF @strCondition IS NULL OR @strCondition=''
	SET @tmpstrCondition=''
ELSE
	BEGIN
		IF CHARINDEX('AND ',LTRIM(@strCondition))=1
			SET @strCondition=RIGHT(@strCondition,LEN(@strCondition)-4)
		IF CHARINDEX('OR ',LTRIM(@strCondition))=1
			SET @strCondition=RIGHT(@strCondition,LEN(@strCondition)-3)
		SET @tmpstrCondition=' WHERE '+@strCondition
	END
--以上为设置WHERE语句

IF @strGroup IS NULL OR @strGroup=''
	SET @tmpstrGroup=''
ELSE
	BEGIN
		SET @tmpstrGroup=' GROUP BY '+@strGroup
		IF @strHaving IS NOT NULL AND @strHaving<>''
			SET @tmpstrGroup=@tmpstrGroup+' HAVING '+@strHaving
	END
--以上为设置GROUP BY语句

DECLARE @tmpFldsubstr nvarchar(1000)     --排序的第一个字段,用于计算总数据量,当@strOrder无数据时有效
IF @Dist=0
	BEGIN
		SET @tmpstrfirst=' SELECT '
		IF @strOrder IS NULL OR @strOrder=''
			BEGIN
				SET @tmpFldsubstr=LEFT(LTRIM(@FldSort),CHARINDEX(CHAR(32),LTRIM(@FldSort)))
				SET @tmpstrfirstCount=' SELECT @Counts=COUNT('+@tmpFldsubstr+')'
			END
		ELSE
			SET @tmpstrfirstCount=' SELECT @Counts=COUNT('+@strOrder+')'
	END
ELSE
	BEGIN
		SET @tmpstrfirst=' SELECT DISTINCT '
		IF @strOrder IS NULL OR @strOrder=''
			BEGIN
				SET @tmpFldsubstr=LEFT(LTRIM(@FldSort),CHARINDEX(CHAR(32),LTRIM(@FldSort)))
				SET @tmpstrfirstCount=' SELECT @Counts=COUNT(DISTINCT '+@tmpFldsubstr+')'
			END
		ELSE
			SET @tmpstrfirstCount=' SELECT @Counts=COUNT(DISTINCT '+@strOrder+')'
	END
--以上通过@Dist设置@Counts

DECLARE @sqlStr nvarchar(3000)     --查询的sql语句
IF @tmpstrGroup=''
	SET @sqlStr=@tmpstrfirstCount+' FROM '+@TblName+@tmpstrCondition
ELSE
	BEGIN
		SET @tmpstrfirstCount=REPLACE(@tmpstrfirstCount,'@Counts=','')
		SET @sqlStr='SELECT @Counts=COUNT(*) FROM ('+@tmpstrfirstCount+'AS tmpF FROM '+@TblName+@tmpstrCondition+@tmpstrGroup+') AS tmpT'
	END
EXEC sp_executesql @sqlStr,N'@Counts int out ',@Counts out     --返回查找到的总数

IF @OnlyCounts=1
	RETURN
--如果@OnlyCounts=1,则直接返回总条数

DECLARE @tmpCounts int 
IF @Counts=0
    SET @tmpCounts=1 
ELSE
    SET @tmpCounts=@Counts

SET @PageCounts=(@tmpCounts+@PageSize-1)/@PageSize
--以上获得分页总数

IF @Page<1
	SET @Page=1
IF @Page>@PageCounts
	SET @Page=@PageCounts
--以上设置分页

DECLARE @tmpsql nvarchar(3000)     --设置最后要查询的SQL语句

IF @Page=1     --当取第一页时,用最快的算法
	SET @tmpsql=@tmpstrfirst+' TOP '+CAST(@PageSize AS nvarchar(50))+' '+@FldName+' FROM '+@TblName+@tmpstrCondition+@tmpstrGroup+' ORDER BY '+@tmpFldSort
IF @Page>1 AND @Page<=@PageCounts/2     --这是要查询的页在总分页数的前半
	BEGIN
		SET @tmpsql='WITH temptbl AS(SELECT TOP '+CAST(@Page*@PageSize AS nvarchar(50))+' ROW_NUMBER() OVER(ORDER BY '+@tmpFldSort+') AS tmpRowIndex,'+@FldName+' FROM '+@TblName+' '+@tmpstrCondition+' '+@tmpstrGroup+') '
		SET @tmpsql=@tmpsql+'SELECT * FROM temptbl WHERE [tmpRowIndex] BETWEEN '+CAST((@Page-1)*@PageSize+1 AS nvarchar(50))+' AND '+CAST((@Page-1)*@PageSize+@PageSize AS nvarchar(50))
	END
IF @Page>1 AND @Page>@PageCounts/2     --从后面查在总分页数的后半数据
	BEGIN
		SET @tmpFldSort=REPLACE(@tmpFldSort,' ASC',' [~1]')
		SET @tmpFldSort=REPLACE(@tmpFldSort,' DESC',' [~2]')
		SET @tmpFldSort=REPLACE(@tmpFldSort,'[~1]','DESC')
		SET @tmpFldSort=REPLACE(@tmpFldSort,'[~2]','ASC')
		--优化后半部分数据查询,把查询条件互换,[~1]为DESC,[~2]为ASC
		SET @tmpsql='WITH temptbl AS(SELECT TOP '+CAST(@Counts-(@Page-1)*@PageSize AS nvarchar(50))+' ROW_NUMBER() OVER(ORDER BY '+@tmpFldSort+') AS tmpRowIndex,'+@FldName+' FROM '+@TblName+' '+@tmpstrCondition+' '+@tmpstrGroup+') '
		SET @tmpsql=@tmpsql+'SELECT * FROM temptbl WHERE [tmpRowIndex] BETWEEN '+CAST(@Counts-((@Page-1)*@PageSize+@PageSize-1) AS nvarchar(50))+' AND '+CAST(@Counts-((@Page-1)*@PageSize) AS nvarchar(50))+' ORDER BY tmpRowIndex DESC'
	END

--SELECT @tmpsql     查看拼接的字符串
EXEC sp_executesql @tmpsql

/*计算时间*/
--SELECT DATEDIFF(MS,@StartTime,GETDATE()) AS [Time]
/**/
SET NOCOUNT OFF
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL Commands in MySQL: Practical ExamplesSQL Commands in MySQL: Practical ExamplesApr 14, 2025 am 12:09 AM

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

How does InnoDB handle ACID compliance?How does InnoDB handle ACID compliance?Apr 14, 2025 am 12:03 AM

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft