search
HomeDatabaseMysql Tutorialsqlserver2005使用row_number() over分页的实现方法

sqlserver2005使用row_number() over分页的实现方法,需要的朋友可以参考下。

语法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)

例子:
代码如下:
select * from (
    select *, ROW_NUMBER() OVER(Order by a.CreateTime DESC ) AS RowNumber from table_name as a
  ) as b
  where RowNumber BETWEEN 1 and 5

将会返回table表

其中有一列名字为 RowNumber, 编号从1开始

示例:
xlh row_num
1700 1
1500 2
1085 3
710 4

有了row_num 编号之后是不是很方便分页呀! 哈哈

只要使用
where RowNumber between
就可以实现分页了 呵呵(从此分页就是这么简单)

例子:
代码如下:
select *
from(
select ROW_NUMBER() OVER( ORDER BY PSIO.CreateTime DESC ) AS RowNumber,PSIO.SeqNo,PSIO.CreateTime from dbo.Output PSIO
inner join Album PPA on PSIO.PPAID=PPA.PPAID
where PPA.PPAID=103--PPAID=3.PPAID
) T where RowNumber BETWEEN 1 and 5 order by 1

在当前select里面不能采用 RowNumber字段,并且不能使用排序

方式一
select top @pageSize * from company where id not in
(select top @pageSize*(@pageIndex-1) id from company)

方式二ROW_NUMBER()OVER

--ROW_NUMBER() 就是生成一个有顺序的行号,而他生成顺序的标准,就是后面紧跟的OVER(ORDER BY ID)
--还必须添加OVER语句以便告诉SQL Server你希望怎样添加行序号。
select getdate()
select * from company where id in (
--搜索出settable表中所有的编号,也就是company表中的id,这里只不过要得到num(即有顺序的编号)
select id from
--搜索出出表中的所有的id,并且新建一列num用来存取排序的编号,并且把这张表赋值给settable
(select id,row_number() over (order by id) as
num from company)
as settable
--添加搜索条件页索引和页大小
where num between (@pageIndex-1)*@pageSize+1 and @pageIndex*@pageSize)
select getdate()

方式三
SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY id asc) AS rownum,
id
FROM company ) AS D
WHERE rownum BETWEEN (@pageIndex-1)*@pageSize+1 AND @pageIndex*@pageSize
ORDER BY id asc

Sql Server 2000的自定义分页,但是在sql server 2000中,要实现显示某一页,就返回那一页数据的效果的方法实在不尽人意.网上很多通用的分页存储过程,但看着就头大.如果使用我前面提到的使用in,not in,top来进行返回特定页,特殊的限制又会比较多(比如ID要递增).现在Sql Server 2005中提供了一个函数ROW_NUMBER(),可以使自定义分页变得简单许多.
我们先来看看ROW_NUMBER()是干什么的.执行下面这段SQL语句:
SELECT [ReportID],[UserName], [ReportID],
[TimeStart], [TimeEnd],ROW_NUMBER() OVER (ORDER BY ReportID) AS RowNo
FROM [ExecutionLog]
很简单,ROW_NUMBER() 就是生成一个顺序的行号,而他生成顺序的标准,就是后面紧跟的OVER(ORDER BY ReportID).现在,你看到了自定义分页的影子了吗?:)下面,我们看看怎么具体应用这个RowNo进行分页.
现在,假设我每一页的数据是10条,我们就可以使用如下所示的SQL语句返回指定页的数据:
@"
SELECT TOP 10 *
FROM
(
SELECT top 10 [InstanceName], [UserName], [ReportID],
[TimeStart], [TimeEnd],ROW_NUMBER() OVER (ORDER BY ReportID) AS RowNo
FROM [ExecutionLog]
) AS A
WHERE RowNo > " + pageIndex*10
pageIndex就是我们需要数据的页数.很简单,不是吗?并且,这种方式几乎没有什么限制,因为他相当于对于任何检索,都生成了一个新的排序列.我们就可以使用该列进行自定义分页.
================
下面举个例子:
ROW_NUMBER函数
  SQL Server2005为我们引入了一个ROW_NUMBER函数。你是否曾经需要为你的查询结果集做行序号?你有时会发现能够为行做序号是一件很有用的事情。从前,你不得不作棘手的事,像创建一个有序号列的临时表,然后把你的SELECT结果插入到这个临时表中。现在,用ROW_NUMBER函数,你就可以获得添加在你的结果集的增加列中的行序号。为了获得行序号,你只要简单的将ROW_NUMBER函数作为一列添加进你的SELECT语句中。你还必须添加OVER语句以便告诉SQL Server你希望怎样添加行序号。
  SELECT ROW_NUMBER() OVER(ORDER BY employee_id) AS 'Row Number', * from
  dbo.employee

结果
Row Number employee_id Firstname Lastname soc_sec
1 5623222 Tim Jones 123-65-8745
2 5632111 Rob Kinkad 456-69-8754
3 6365666 Jim Miller 236-56-8989
4 7563333 Joe Roberts 564-89-5555

  这个查询返回所有的雇员和一个显示每条记录在哪一行的一个序号。OVER语句使SQL Server基于employee_id列增加行序号。换句话说,产生了行序号,就好像数据按employee_id做了排序。这是很重要的一点,因为你仍然可以改变SELECT的排序顺序。以下面的查询为例:
  SELECT ROW_NUMBER() OVER(ORDER BY employee_id) AS 'Row Number', * from
  dbo.employee
  ORDER BY soc_sec

结果
Row Number employee_id Firstname Lastname soc_sec
1 5623222 Tim Jones 123-65-8745
3 6365666 Jim Miller 236-56-8989
2 5632111 Rob Kinkad 456-69-8754
4 7563333 Joe Roberts 564-89-5555

  注意第二个结果集数据是按社会安全编号来排序的,但是行号仍然创建得好像数据是按employee_id排序的。
-------------------------------分页存储过程
IF EXISTS (SELECT * FROM sysobjects where name='P_student')
DROP PROCEDURE P_student
go
CREATE PROCEDURE P_student
@startIndex INT,
@pageSize INT
AS
begin WITH studentList AS (
SELECT ROW_NUMBER() OVER (ORDER BY O.stuid ) Row,
O.stuid,O.stuname,O.stuage,O.stuinfo
from student O)
SELECT Row, stuid,stuname,stuage,stuinfo
FROM studentList
WHERE Row between @startIndex and @startIndex+@pageSize-1
end

-------------------分页2---------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Deer_Page]
(
@startIndex INT
,@pageSize INT
,@strSql varchar(5000) ---查询条件
,@TableName varchar(50)
,@DoCount AS bit=1 -- 0值返回记录总数, 非 0 值则返回记录
)
AS
begin tran
IF @DoCount=0
Goto GetCount
Else
Goto GetSearch
GetCount: --返回记录总数
DECLARE @SearchSql AS Nvarchar(4000)
SET @SearchSql= 'SELECT Count(*) AS Total FROM '+@TableName+' WHERE IntReserve1=0'
exec sp_executesql @SearchSql
--print @SearchSql
COMMIT TRAN
return
GetSearch: --返回记录
DECLARE @SqlQuery varchar(4000)
SET @SqlQuery='SELECT * FROM
(SELECT ROW_NUMBER() OVER (ORDER BY O.ID ) Row, * from '+@TableName+' O Where IntReserve1=0) as temp
WHERE Row BETWEEN '+cast(@startIndex as varchar) +' and '+cast(@startIndex+@pageSize-1 as varchar)+ @strsql
---print @SqlQuery
execute(@SqlQuery)
COMMIT TRAN
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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)