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

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

/******************/
--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

 用法如下:

--单表查询
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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值