基于Sql Server通用分页存储过程的解决方法

sql server2000分页方式很多,效率吗  当到达10万级以上就有些吃力了,这里暂时不例出来了

sql server2005以上就有了row_number 也是一大进步,详情如下参考

复制代码 代码如下:

sql server2005通用分页存储过程

create procedure [dbo].[common_getpagedlist]
(
@tablename nvarchar(100), –表名
@columnnames nvarchar(1000) = ‘*’, –字段名集合(全部字段为*,其它逗号分隔)
@orderclause nvarchar(1000), –排序从句(不包含order by)
@whereclause nvarchar(1000) =n’ 1=1 ‘,    –条件从句(不包含where)
@pagesize int = 0, –每页记录数(0为所有)
@pageindex int = 1,     –页索引(从1开始)
@totalrecord int output     –返回总记录数
)
as

begin
if (@columnnames is null or @columnnames=”) set @columnnames=’ * ‘
if (@whereclause is null or @whereclause=”) set @whereclause=’ 1=1 ‘
if (@orderclause is null or @orderclause=”) set @orderclause=’ id desc ‘

–处理开始点和结束点
declare @startrecord int;
declare @endrecord int;
declare @totalcountsql nvarchar(1200);
declare @sqlstring nvarchar(4000);   

–统计记录
if(@totalrecord is null or @totalrecord>=0)
begin
set @totalcountsql= n’select @totalrecord = count(*) from ‘ + @tablename +’ where ‘+@whereclause;
–select @totalcountsql
exec sp_executesql @totalcountsql,n’@totalrecord int out’,@totalrecord output;–返回总记录数
end

if @pagesize>0
begin   
if @pageindex<1 set @pageindex=1
set @startrecord = (@pageindex-1)*@pagesize + 1   
set @endrecord = @startrecord + @pagesize – 1
set @sqlstring = n’select row_number() over (order by ‘+ @orderclause +’) as rowid,’+@columnnames+’ from ‘+ @tablename+’ where ‘+@whereclause;
set @sqlstring =’select * from (‘ + @sqlstring + ‘) as t where rowid between ‘ + ltrim(str(@startrecord)) + ‘ and ‘ + ltrim(str(@endrecord));
end
else
begin
set @sqlstring=’select ‘+@columnnames+’ from ‘+ @tablename+’ where ‘+@whereclause +’ order by ‘+@orderclause
end
–select @sqlstring
exec(@sqlstring)
end

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐