SQL Server利用RowNumber()内置函数与Over关键字实现通用分页存储过程(支持单表或多表结查集分页)

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
简介:

SQL Server利用RowNumber()内置函数与Over关键字实现通用分页存储过程,支持单表或多表结查集分页,存储过程如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/******************/
--Author:梦在旅途(www.Zuowenjun.cn)
--CreateDate:2015-06-02
--Function:分页获取数据
/******************/
create  procedure  [dbo].[sp_DataPaging]
(
@selectsql  nvarchar(200), --查询字段SQL,不含select,支持灵活写法,如:col1,col3,isnull(col4,'') as col4
@fromsql    nvarchar(500), --查询表及条件SQL,不含from,若包含条件请加上where,如:table where col1='test'
@orderbysql nvarchar(100), --查询排序SQL,不含order by,如:id order by desc
@pagesize    int =20, --每页显示记录数
@pageno      int =1, --当前查询页码,从1开始
@returnrecordcount  bit =1  --是否需要返回总记录数,若设为1,则返回两个结果表
)
as
begin
 
     declare  @sqlcount nvarchar(500),@sqlstring nvarchar( max )
     
     set  @sqlstring=N 'from (select row_number() over (order by '  + @orderbysql + N ') as rowId,'  + @selectsql + N ' from '
                 + @fromsql +N ') as t'
     if(@returnrecordcount=1)
     begin
         set  @sqlcount=N 'select count(rowId) as resultcount '  + @sqlstring
         exec (@sqlcount)
     end
 
     set  @sqlstring=N 'select * '  + @sqlstring +  ' where rowId between '  convert (nvarchar(50),(@pageno-1)*@pagesize+1)+ ' and ' + convert (nvarchar(50),@pageno*@pagesize)
     
     exec (@sqlstring)
     
end

 用法如下:

1
2
3
4
5
6
7
--单表查询
exec  [dbo].[sp_DataPaging]  '*' , 'AssetDetail' , 'assetsingleno' ,10,1
 
--多表查询
exec  [dbo].[sp_DataPaging]  'a.*' , 'Inventory a left join AssetDetail b
on a.StoreNo=b.StoreNo and a.CompanyID=b.CompanyID
inner join Asset c on b.AssetID=c.ID and b.CompanyID=c.CompanyID' , 'a.id' ,20,3,1

结果显示如下(如上多表查询):

本文转自 梦在旅途 博客园博客,原文链接:http://www.cnblogs.com/zuowj/p/4546079.html  ,如需转载请自行联系原作者

相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情: https://www.aliyun.com/product/rds/sqlserver
相关文章
|
27天前
|
存储 SQL Go
sqlserver存储过程
sqlserver存储过程
19 0
|
28天前
|
存储 SQL 数据库
sqlserver中常用的几个存储过程
sqlserver中常用的几个存储过程
47 0
|
3月前
|
SQL 存储 关系型数据库
sql语句,索引,视图,存储过程
sql语句,索引,视图,存储过程
27 0
|
4月前
|
SQL 数据库
SQL Server 单表数据查询
SQL Server 单表数据查询
103 1
|
3月前
|
存储 SQL 缓存
4.2.1 SQL语句、索引、视图、存储过程
4.2.1 SQL语句、索引、视图、存储过程
|
26天前
|
存储 SQL 数据库
sql serve存储过程
sql serve存储过程
14 0
|
4月前
|
SQL Serverless
SQL Sever 单表数据查询(下)
SQL Sever 单表数据查询(下)
46 1
|
1月前
|
存储 SQL
物料清单应用输入模板的SQL存储过程设计
物料清单应用输入模板的SQL存储过程设计
|
2月前
|
SQL 人工智能 运维
数据库基础入门 — SQL排序与分页
数据库基础入门 — SQL排序与分页
25 0
|
3月前
|
SQL 存储 数据可视化
【开源项目推荐】通用SQL数据血缘分析工具——Sqllineage
【开源项目推荐】通用SQL数据血缘分析工具——Sqllineage
117 0