Home > Database > Mysql Tutorial > sqlserver 通用分页存储过程

sqlserver 通用分页存储过程

WBOY
Release: 2016-06-07 17:58:56
Original
1038 people have browsed it

sqlserver 通用分页存储过程,用存储过程可以提高效率与节约时间。

代码如下:
create proc commonPagination
@columns varchar(500), --要显示的列名,用逗号隔开
@tableName varchar(100), --要查询的表名
@orderColumnName varchar(100), --排序的列名
@order varchar(50), --排序的方式,升序为asc,降序为 desc
@where varchar(100), --where 条件,如果不带查询条件,请用 1=1
@pageIndex int, --当前页索引
@pageSize int, --页大小(每页显示的记录条数)
@pageCount int output --总页数,输出参数
as
begin
declare @sqlRecordCount nvarchar(1000) --得到总记录条数的语句
declare @sqlSelect nvarchar(1000) --查询语句
set @sqlRecordCount=N'select @recordCount=count(*) from '
+@tableName + ' where '+ @where
declare @recordCount int --保存总记录条数的变量
exec sp_executesql @sqlRecordCount,N'@recordCount int output',@recordCount output
--动态 sql 传参
if( @recordCount % @pageSize = 0) --如果总记录条数可以被页大小整除
set @pageCount = @recordCount / @pageSize --总页数就等于总记录条数除以页大小
else --如果总记录条数不能被页大小整除
set @pageCount = @recordCount / @pageSize + 1 --总页数就等于总记录条数除以页大小加1
set @sqlSelect =
N'select '+@columns+' from (
select row_number() over (order by '
+@orderColumnName+' '+@order
+') as tempid,* from '
+@tableName+' where '+ @where
+') as tempTableName where tempid between '
+str((@pageIndex - 1)*@pageSize + 1 )
+' and '+str( @pageIndex * @pageSize)
exec (@sqlSelect) --执行动态Sql
end
go
--以下是调用示例
use pubs
go
declare @pageCount int
exec commonPagination
'job_id,job_desc','jobs','job_id',
'asc','1=1',2,2,@pageCount output
select '总页数为:' + str(@pageCount)
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template