一聚教程网:一个值得你收藏的教程网站

热门教程

两款sql 分页存储过程代码

时间:2022-11-14 23:38:20 编辑:袖梨 来源:一聚教程网

文章收藏了两款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 int

set @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

热门栏目