文章收藏了两款sql 分页存储过程代码,这二款存储过程是二款高效分页存储过程代码,如果你觉得自己写的语句不够,强的话,可以利用我们现成的高效分页存储过程实例代码。
create procedure pages
@tablenames varchar(200), --表名,可以是多个表,但不能用别名
@primarykey varchar(100), --主键,可以为空,但@order为空时该值不能为空
@fields varchar(800), --要取出的字段,可以是多个表的字段,可以为空,为空表示select *
@pagesize int, --每页记录数
@currentpage int, --当前页,0表示第1页
@filter varchar(200) = '', --条件,可以为空,不用填 where
@order varchar(200) = '' --排序,可以为空,为空默认按主键升序排列,不用填 order by
as
begin
declare @toprow varchar(12)
declare @temppagesize varchar(12)
if(len(@order)>0)
begin
set @order=' order by '+@order
end
else
begin
set @order=''
end
if (len(@filter)<1)
begin
set @filter=' 1=1'
end
if(@currentpage-1<=0)
set @currentpage=0
set @toprow= rtrim(ltrim(str(@pagesize*(@currentpage-1))))
set @temppagesize= rtrim(ltrim(str(@pagesize)))
exec('
declare @temptable table(rownum int identity(1,1),gid varchar(12))'+'
declare @datatable table(gid varchar(12))'+'
declare @timer datetime'+'
set @timer = getdate() '+'
set nocount on '+'
insert into @temptable(gid) select '+@primarykey+' from '+@tablenames+' where '+@filter+@order+'
insert into @datatable(gid) select top '+@temppagesize+'gid from @temptable where rownum>'+@toprow+'
set rowcount '+@temppagesize+'select '+@fields+' from '+@tablenames+' where '+@filter+' and '+@primarykey+' in (select gid from @datatable)'+@order+'
set rowcount 0'+'
print(datediff(millisecond, @timer, getdate()))')
print('insert into @temptable(gid) select '+@primarykey+' from '+@tablenames+' where '+@filter+@order)
print('select '+@fields+' from '+@tablenames+' where '+@filter+' and '+@primarykey+' in(select gid from @datatable) '+@order)
end
go
实例代码二
alter procedure [dbo].[common_procedure_selectwithpage]
@sql varchar(5000),
@currentpageno int,
@pagesize int,
@totalnum int output
as
set nocount on
declare @sqlcmd varchar(5000)
------------------------------------------ --查询数据
set @sqlcmd = 'select * from (' + @sql + ') a where rowindex between ' + convert(varchar,(@currentpageno-1) * @pagesize + 1) + ' and ' + convert(varchar,@currentpageno * @pagesize)
exec(@sqlcmd) print (@sqlcmd)
------------------------------------------ --求记录总数
if @totalnum = -1
begin
create table #temp1(num int)
insert into #temp1
exec('select count(*) from (' + @sql + ') a')
select @totalnum=(select * from #temp1)
drop table #temp1
end用法很简单,但必须在传入的sql中使用row_number() over(...) as rowindex :
declare @sql varchar(5000)
declare @currentpageno int
declare @pagesize int
declare @totalnum intset @currentpageno = 100
set @pagesize = 10
set @totalnum = -1
set @sql = ' select *, row_number() over (order by 排序字段) as rowindex from 表名 a with (nolock) 'exec [dbo].[common_procedure_selectwithpage] @sql,@currentpageno,@pagesize,@totalnum output
select @totalnum
我最强舞者 (I, Best Dancer)安卓版v8
我最强舞者(I, Best Dancer)是一款休闲放置类手
迷你世界国服版本2024 v1.43.0
迷你世界国服版本2024是一款自由度非常高的沙盒游戏,玩法和
烹饪乐园 安卓版v1.23.6
烹饪乐园(Cooking Town)是一款非常好玩的餐厅模拟
迷你世界小米服 最新安卓版v1.43.0
迷你世界小米版是由迷你玩科技开发的休闲模拟经营类游戏。此版本
布娃娃Sprunki沙盒 安卓版v0.0.1
布娃娃Sprunki沙盒是一个非常有趣的沙盒游戏,复古简约的