建立好如下的存储过程,以后要分页,直接调用改存储过程就可以了。
注意:数据量大、性能要求高的,请个性化处理。
复制代码 代码如下:
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