Home Database Mysql Tutorial 2分法-通用存储过程分页(top max模式)版本_MySQL

2分法-通用存储过程分页(top max模式)版本_MySQL

Jun 01, 2016 pm 02:05 PM
set storage model Version process Universal

--/*-----存储过程 分页处理 孙伟 2005-03-28创建 -------*/
--/*----- 对数据进行了2分处理使查询前半部分数据与查询后半部分数据性能相同 -------*/
--/*-----存储过程 分页处理 孙伟 2005-04-21修改 添加Distinct查询功能-------*/
--/*-----存储过程 分页处理 孙伟 2005-05-18修改 多字段排序规则问题-------*/
--/*-----存储过程 分页处理 孙伟 2005-06-15修改 多字段排序修改-------*/
--/*-----存储过程 分页处理 孙伟 2005-12-13修改 修改数据分页方式为top max模式 性能有极大提高-------*/
--/*-----缺点:相对之前的not in版本主键只能是整型字段,如主键为GUID类型请使用not in 模式的版本-------*/
CREATE PROCEDURE dbo.proc_ListPageInt
(
@tblName nvarchar(200), ----要显示的表或多个表的连接
@fldName nvarchar(500) = '*', ----要显示的字段列表
@pageSize int = 10, ----每页显示的记录个数
@page int = 1, ----要显示那一页的记录
@pageCount int = 1 output, ----查询结果分页后的总页数
@Counts int = 1 output, ----查询到的记录数
@fldSort nvarchar(200) = null, ----排序字段列表或条件
@Sort bit = 0, ----排序方法,0为升序,1为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记)--程序传参如:' SortA Asc,SortB Desc,SortC ')
@strCondition nvarchar(1000) = null, ----查询条件,不需where
@ID nvarchar(150), ----主表的主键
@Dist bit = 0 ----是否添加查询字段的 DISTINCT 默认0不添加/1添加
)
AS
SET NOCOUNT ON
Declare @sqlTmp nvarchar(1000) ----存放动态生成的SQL语句
Declare @strTmp nvarchar(1000) ----存放取得查询结果总数的查询语句
Declare @strID nvarchar(1000) ----存放取得查询开头或结尾ID的查询语句

Declare @strSortType nvarchar(10) ----数据排序规则A
Declare @strFSortType nvarchar(10) ----数据排序规则B

Declare @SqlSelect nvarchar(50) ----对含有DISTINCT的查询进行SQL构造
Declare @SqlCounts nvarchar(50) ----对含有DISTINCT的总数查询进行SQL构造


if @Dist = 0
begin
set @SqlSelect = 'select '
set @SqlCounts = 'Count(*)'
end
else
begin
set @SqlSelect = 'select distinct '
set @SqlCounts = 'Count(DISTINCT ' @ID ')'
end


if @Sort=0
begin
set @strFSortType=' ASC '
set @strSortType=' DESC '
end
else
begin
set @strFSortType=' DESC '
set @strSortType=' ASC '
end

--------生成查询语句--------
--此处@strTmp为取得查询结果数量的语句
if @strCondition is null or @strCondition='' --没有设置显示条件
begin
set @sqlTmp = @fldName ' From ' @tblName
set @strTmp = @SqlSelect ' @Counts=' @SqlCounts ' FROM ' @tblName
set @strID = ' From ' @tblName
end
else
begin
set @sqlTmp = @fldName 'From ' @tblName ' where (1>0) ' @strCondition
set @strTmp = @SqlSelect ' @Counts=' @SqlCounts ' FROM ' @tblName ' where (1>0) ' @strCondition
set @strID = ' From ' @tblName ' where (1>0) ' @strCondition
end

----取得查询结果总数量-----
exec sp_executesql @strTmp,N'@Counts int out ',@Counts out
declare @tmpCounts int
if @Counts = 0
set @tmpCounts = 1
else
set @tmpCounts = @Counts

--取得分页总数
set @pageCount=(@tmpCounts @pageSize-1)/@pageSize

/**//**当前页大于总页数 取最后一页**/
if @page>@pageCount
set @page=@pageCount

--/*-----数据分页2分处理-------*/
declare @pageIndex int --总数/页大小
declare @lastcount int --总数%页大小

set @pageIndex = @tmpCounts/@pageSize
set @lastcount = @tmpCounts%@pageSize
if @lastcount > 0
set @pageIndex = @pageIndex 1
else
set @lastcount = @pagesize

--//***显示分页
if @strCondition is null or @strCondition='' --没有设置显示条件
begin
if @pageIndex begin
if @page=1
set @strTmp=@SqlSelect ' top ' CAST(@pageSize as VARCHAR(4)) ' ' @fldName ' from ' @tblName
' order by ' @fldSort ' ' @strFSortType
else
begin
set @strTmp=@SqlSelect ' top ' CAST(@pageSize as VARCHAR(4)) ' ' @fldName ' from ' @tblName
' where ' @ID ' ' order by ' @fldSort ' ' @strFSortType ') AS TBMinID)'
' order by ' @fldSort ' ' @strFSortType
end
end
else
begin
set @page = @pageIndex-@page 1 --后半部分数据处理
if @page set @strTmp=@SqlSelect ' * from (' @SqlSelect ' top ' CAST(@lastcount as VARCHAR(4)) ' ' @fldName ' from ' @tblName
' order by ' @fldSort ' ' @strSortType ') AS TempTB' ' order by ' @fldSort ' ' @strFSortType
else
set @strTmp=@SqlSelect ' * from (' @SqlSelect ' top ' CAST(@pageSize as VARCHAR(4)) ' ' @fldName ' from ' @tblName
' where ' @ID ' >(select max(' @ID ') from(' @SqlSelect ' top ' CAST(@pageSize*(@page-2) @lastcount as Varchar(20)) ' ' @ID ' from ' @tblName
' order by ' @fldSort ' ' @strSortType ') AS TBMaxID)'
' order by ' @fldSort ' ' @strSortType ') AS TempTB' ' order by ' @fldSort ' ' @strFSortType
end
end

else --有查询条件
begin
if @pageIndex begin
if @page=1
set @strTmp=@SqlSelect ' top ' CAST(@pageSize as VARCHAR(4)) ' ' @fldName ' from ' @tblName
' where 1=1 ' @strCondition ' order by ' @fldSort ' ' @strFSortType
else
begin
set @strTmp=@SqlSelect ' top ' CAST(@pageSize as VARCHAR(4)) ' ' @fldName ' from ' @tblName
' where ' @ID ' ' where (1=1) ' @strCondition ' order by ' @fldSort ' ' @strFSortType ') AS TBMinID)'
' ' @strCondition ' order by ' @fldSort ' ' @strFSortType
end
end
else
begin
set @page = @pageIndex-@page 1 --后半部分数据处理
if @page set @strTmp=@SqlSelect ' * from (' @SqlSelect ' top ' CAST(@lastcount as VARCHAR(4)) ' ' @fldName ' from ' @tblName
' where (1=1) ' @strCondition ' order by ' @fldSort ' ' @strSortType ') AS TempTB' ' order by ' @fldSort ' ' @strFSortType
else
set @strTmp=@SqlSelect ' * from (' @SqlSelect ' top ' CAST(@pageSize as VARCHAR(4)) ' ' @fldName ' from ' @tblName
' where ' @ID ' >(select max(' @ID ') from(' @SqlSelect ' top ' CAST(@pageSize*(@page-2) @lastcount as Varchar(20)) ' ' @ID ' from ' @tblName
' where (1=1) ' @strCondition ' order by ' @fldSort ' ' @strSortType ') AS TBMaxID)'
' ' @strCondition ' order by ' @fldSort ' ' @strSortType ') AS TempTB' ' order by ' @fldSort ' ' @strFSortType
end
end

------返回查询结果-----
exec sp_executesql @strTmp
--print @strTmp
SET NOCOUNT OFF
GO
调用方法列子:
/**////


/// 通用分页数据读取函数
/// 注意:在函数调用外部打开和关闭连接,以及关闭数据读取器
///

/// SqlCommand对象
/// 查询的表/表联合
/// 要查询的字段名
/// 每页数据大小
/// 当前第几页
/// 排序字段
/// 排序顺序0降序1升序
/// 过滤条件
/// 主表主键
/// 返回的SqlDataReader ref
public static void CutPageData(SqlConnection conn, ref SqlCommand comm, string _tblName, string _fldName, int _pageSize, int _page, string _fldSort, int _Sort, string _strCondition, string _ID, ref SqlDataReader _dr)
{
//注意:在函数调用外部打开和关闭连接,以及关闭数据读取器
//comm = new SqlCommand("proc_ListPage",conn);
//comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("@tblName", SqlDbType.NVarChar, 200);
comm.Parameters["@tblName"].Value = _tblName;
comm.Parameters.Add("@fldName", SqlDbType.NVarChar, 500);
comm.Parameters["@fldName"].Value = _fldName;
comm.Parameters.Add("@pageSize", SqlDbType.Int);
comm.Parameters["@pageSize"].Value = _pageSize;
comm.Parameters.Add("@page", SqlDbType.Int);
comm.Parameters["@page"].Value = _page;
comm.Parameters.Add("@fldSort", SqlDbType.NVarChar, 200);
comm.Parameters["@fldSort"].Value = _fldSort;
comm.Parameters.Add("@Sort", SqlDbType.Bit);
comm.Parameters["@Sort"].Value = _Sort;
comm.Parameters.Add("@strCondition", SqlDbType.NVarChar, 1000);
comm.Parameters["@strCondition"].Value = _strCondition;
comm.Parameters.Add("@ID", SqlDbType.NVarChar, 150);
comm.Parameters["@ID"].Value = _ID;
comm.Parameters.Add("@Counts", SqlDbType.Int, 0);
comm.Parameters["@Counts"].Direction = ParameterDirection.Output;
comm.Parameters.Add("@pageCount", SqlDbType.Int, 0);
comm.Parameters["@pageCount"].Direction = ParameterDirection.Output;

_dr = comm.ExecuteReader();
}
调用例如:
CutPageData(conn, ref comm, "VOX_CDSinger", "id, cdsinger, cdsingertype, area, cdsingerreadme", 15, page, "id", 1, strFilter, "id", ref dr);
对应说明:
CutPageData(数据连接对象, ref Sqlcommand对象, "需要表或视图名称", "要查询的字段", 每页读取数据条数, 当前页, "排序字段可多字段如(addtime desc, visitcounts注意这里最后一个字段不加desc或asc 最后一个字段对应于后面的排序规则)", 排序方式(1 desc 0 asc), where条件(这里不再添加where条件添加如:' and visitcounts>100'), 表主键, ref 返回的SqlDataReader对象);

这里的调用同样适用于之前的not in版本.


呵呵 这里献给大家 圣诞快乐 !

Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does WeChat's Do Not Disturb mode do? What does WeChat's Do Not Disturb mode do? Feb 23, 2024 pm 10:48 PM

What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

Tutorial on updating curl version under Linux! Tutorial on updating curl version under Linux! Mar 07, 2024 am 08:30 AM

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Check the Kirin operating system version and kernel version Check the Kirin operating system version and kernel version Feb 21, 2024 pm 07:04 PM

Checking the Kylin operating system version and kernel version In the Kirin operating system, knowing how to check the system version and kernel version is the basis for system management and maintenance. Method 1 to check the Kylin operating system version: Use the /etc/.kyinfo file. To check the Kylin operating system version, you can check the /etc/.kyinfo file. This file contains operating system version information. Execute the following command: cat/etc/.kyinfo This command will display detailed version information of the operating system. Method 2: Use the /etc/issue file Another way to check the operating system version is by looking at the /etc/issue file. This file also provides version information, but may not be as good as the .kyinfo file

Simple steps to update pip version: done in 1 minute Simple steps to update pip version: done in 1 minute Jan 27, 2024 am 09:45 AM

Done in one minute: How to update the pip version, specific code examples are required. With the rapid development of Python, pip has become a standard tool for Python package management. However, as time goes by, pip versions are constantly updated. In order to be able to use the latest features and fix possible security vulnerabilities, it is very important to update the pip version. This article will explain how to quickly update pip in one minute and provide specific code examples. First, we need to open a command line window. In Windows systems, you can use

How to easily check the installed version of Oracle How to easily check the installed version of Oracle Mar 07, 2024 am 11:27 AM

How to easily check the installed version of Oracle requires specific code examples. As a software widely used in enterprise-level database management systems, the Oracle database has many versions and different installation methods. In our daily work, we often need to check the installed version of the Oracle database for corresponding operations and maintenance. This article will introduce how to easily check the installed version of Oracle and give specific code examples. Method 1: Through SQL query in the Oracle database, we can

Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Mar 07, 2024 pm 10:43 PM

This website reported on March 7 that Dr. Zhou Yuefeng, President of Huawei's Data Storage Product Line, recently attended the MWC2024 conference and specifically demonstrated the new generation OceanStorArctic magnetoelectric storage solution designed for warm data (WarmData) and cold data (ColdData). Zhou Yuefeng, President of Huawei's data storage product line, released a series of innovative solutions. Image source: Huawei's official press release attached to this site is as follows: The cost of this solution is 20% lower than that of magnetic tape, and its power consumption is 90% lower than that of hard disks. According to foreign technology media blocksandfiles, a Huawei spokesperson also revealed information about the magnetoelectric storage solution: Huawei's magnetoelectronic disk (MED) is a major innovation in magnetic storage media. First generation ME

How to tell whether the dp interface is 1.2 or 1.4? How to tell whether the dp interface is 1.2 or 1.4? Feb 06, 2024 am 10:27 AM

The DP interface is an important interface cable in the computer. When using the computer, many users want to know how to check whether the DP interface is 1.2 or 1.4. In fact, they only need to check it in GPU-Z. How to determine whether the dp interface is 1.2 or 1.4: 1. First, select "Advanced" in GPU-Z. 2. Look at "Monitor1" in "General" under "Advanced", you can see the two items "LinkRate (current)" and "Lanes (current)". 3. Finally, if 8.1Gbps×4 is displayed, it means DP1.3 version or above, usually DP1.4. If it is 5.4Gbps×4, then

See all articles