通用分页存储过程高效动态表

if exists(select * from sysobjects where name='pagedQueryProc')
begin
	drop proc pagedQueryProc
	print 'exists'
end
else 
print 'not exists'
go

create proc pagedQueryProc
@pageIndex int,
@pageSize int ,
@tableName varchar(30)
as
declare @strSql nvarchar(3000);
declare @columnsName varchar(30);
declare @totalCount int;
declare @totalPage int;
declare @strCountSql nvarchar(1000);
   
	select top 1  @columnsName=columns.name from syscolumns as columns,sysobjects as objects  where columns.id=objects.id and objects.name=@tableName;
	
	set @strCountSql='select @totalCount=count(1) from '+@tableName;

    exec sp_executesql @strCountSql,N'@totalCount int output',@totalCount OUTPUT;


	set @totalPage =@totalCount/@pageSize;
	
	
	if  (@totalCount%@pageSize)<>0
		begin
			set @totalPage=@totalPage+1;

		end
	


	if   @pageIndex>1 and  @pageIndex<=@totalPage
		begin
				set @strSql =' select  top '+str(@pageSize) +' *  from '+ @tableName+' where '+@columnsName+' > (select max('+@columnsName+') from '+@tableName+' where '+@columnsName+' in(select top ('+str(@pageSize*(@pageIndex-1))+') '+@columnsName+' from '+@tableName+' order by '+@columnsName+' asc)) order by '+@columnsName+' asc';
		end
	else 
		begin
				set @strSql =' select  top '+str(@pageSize) +' *  from '+ @tableName+' order by '+@columnsName+' asc'
		end 
   exec sp_executesql @strSql
go


exec pagedQueryProc 1,20,'card'  ---你只需要调用就可以了  动态分页        传入三个参数    1.分页当前页数
                                                                                                                           --   2.一页显示记录数
                                     											      --3.需查询的表名

								--是用了max函数进行分页
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值