MYSQL5 分页存储过程

CREATE PROCEDURE PageDiv(
IN tableName varchar(100),
IN filedsNames varchar(500),
IN pageSize int,
IN pageIndex int,
IN strWhere varchar(500),
IN sortName varchar(500)
)

BEGIN
/*
**************过程简介**************
MYSQL5.0通用分页存储过程
作者:范景及 EMAIL:[email protected]
日期:2009-03-08,妇女节完成哒,嘿嘿^^V
说明:该过程实现了分页功能。支持where条件及order排序,但不支持group分组及多表级联查询
由于MYSQL目前无法获取动态SQL返回值(需临时表支持,实现起来太复杂了,晕一个先@@)
所以将总记录数及当前页数首先进行查询,然后再将总记录数及页数放到每一条记录中
**************参数说明**************
表名
IN tableName varchar(100),
字段名,多个字段以,分隔
IN filedsNames varchar(100),
每页显示记录数
IN pageSize int,
当前页
IN pageIndex int,
where条件,多个条件以,分隔
IN strWhere varchar(500),
排序,多个排序以,分隔
IN sortName varchar(500),

**************调用方法**************
call PageDiv('t_user','vcName,vcPassword',3,1,'','')
*/
DECLARE filedlist varchar(500);/*字段列表*/
DECLARE counts int default 0;/*总记录数*/
DECLARE intPages int default 0;/*总页数*/
DECLARE strPages varchar(20);/*总页数*/

/*获取总记录数*/
if strWhere=''||strWhere=null then
set @sqlStr=concat("select count(*) into @counts from ",tableName);
else
set @sqlStr=concat("select count(*) into @counts from ",tableName," where ",strWhere);
end if;
PREPARE STMT FROM @sqlStr;
EXECUTE STMT;

/*获取总页数*/
if strWhere=''||strWhere=null then
set @sqlStr=concat("select count(*)/",pageSize," into @intPages from ",tableName);
else
set @sqlStr=concat("select count(*)/",pageSize," into @intPages from ",tableName," where ",strWhere);
end if;
PREPARE STMT FROM @sqlStr;
EXECUTE STMT;

/*总页数返回值小于1的,均按1取值;大于1但有小数位的,则通过截取字符串的方式加1*/
if(@intPages<1) then
set @intPages=1;
elseif(@intPages>1) then
set @strPages=cast(@intPages as char);
if(INSTR(@strPages,".")>=0) then
set @strPages=LEFT(@strPages,INSTR(@strPages,".")-1);
set @intPages=cast(@strPages as char)+1;
end if;
end if;

/*分页操作*/
if filedsNames=''||filedsNames=null THEN
set filedlist='*';
else
set filedlist=filedsNames;
end if;

if strWhere=''||strWhere=null then
if sortName=''||sortName=null then
set @strSQL=concat('SELECT ',filedlist,',',@counts,' as totalRecord ,',@intPages,' as totalPage FROM ',tableName,' LIMIT ',(pageIndex-1)*pageSize,',',pageSize);
else
set @strSQL=concat('SELECT ',filedlist,',',@counts,' as totalRecord ,',@intPages,' as totalPage FROM ',tableName,' ORDER BY ',sortName,' LIMIT ',(pageIndex-1)*pageSize,',',pageSize);
end if;
else
if sortName=''||sortName=null then
set @strSQL=concat('SELECT ',filedlist,',',@counts,' as totalRecord ,',@intPages,' as totalPage FROM ',tableName,' WHERE ',strWhere,' LIMIT ',(pageIndex-1)*pageSize,',',pageSize);
else
set @strSQL=concat('SELECT ',filedlist,',',@counts,' as totalRecord ,',@intPages,' as totalPage FROM ',tableName,' WHERE ',strWhere,' ORDER BY ',sortName,' LIMIT ',(pageIndex-1)*pageSize,',',pageSize);
end if;
end if;
PREPARE stmt_strSQL FROM @strSQL;
EXECUTE stmt_strSQL;
DEALLOCATE PREPARE stmt_strSQL;
END

猜你喜欢

转载自xiaof0535.iteye.com/blog/1489773