承接国内外服务器租用托管、定制开发、网站代运营、网站seo优化托管接单、网站代更新,新老站点皆可!!咨询QQ:3787320601

怎样使用SQLServer实现分页查询

管理员 2023-04-25 09:28:47 网站建设 47 ℃ 0 评论 2237字 收藏

怎样使用SQLServer实现分页查询

Paging query is one of the most basic functions of SQL. In order to improve the query efficiency, we can use paging query to query only several rows of data each time. In this way, we can save more time and space than loading all query data into memory at once. In this paper, we will introduce how to use SQLServer to realize paging query.

(A)Using rownumber

The most ideal and reliable way for SQL Server to implement paging query is to use the rownumber function of SQL. The syntax is as follows:

SELECT *

FROM (SELECT * , ROW_NUMBER() OVER (ORDER BY ShipmentDate) as rowNum

FROM TBL_SHIPMENT ) AS pagedResult

WHERE rowNum BETWEEN @startPage AND @endPage

The query results returned by this method are very accurate and meet the requirements of our paging query. In the above syntax, we can see that two parameters @startPage and @endPage are used as the start and end page conditions. It also contains an ordering clause that orders the rows by column shipmentdate (in SQL Server 2012 and above, we can use the OFFSET‐FETCH clause to sort results).

(B)Using top

Besides the rownumber method mentioned above, we can also use the TOP clause of SQL to fetch a certain number of rows from an ordered set of rows. The syntax is as follows:

SELECT TOP (@pagesize) *

FROM (SELECT * , ROW_NUMBER() OVER (ORDER BY ShipmentDate) as rowNum

FROM TBL_SHIPMENT ) AS paged

WHERE rowNum > @startPage

This syntax is also commonly used in paging query. The main difference between this syntax and the rownumber method mentioned above is that we don’t need to calculate the @endPage parameter every time here. When we page results in batches, we just need to pass the page size parameter.

(C)Conclusion

To sum up, the two methods mentioned above can help us realize the paging query of SQLServer very well. There are a variety of ways to implement it depending on the actual situation, and the above explanation is just a part of it. Therefore, we need to choose a more suitable method according to the actual situation and conditions of our project.

文章来源:丸子建站

文章标题:怎样使用SQLServer实现分页查询

https://www.wanzijz.com/view/19242.html

X

截屏,微信识别二维码

微信号:weimawl

(点击微信号复制,添加好友)

打开微信