/*
--名称:MYSQL版查询分页存储过程
--输入参数:@fields -- 要查询的字段用逗号隔开
--输入参数:@tables -- 要查询的表
--输入参数:@where -- 查询条件
--输入参数:@orderby -- 排序字段
--输出参数:@page -- 当前页计数从1开始
--输出参数:@pagesize -- 每页大小
--输出参数:@totalcount -- 总记录数
--输出参数:@pagecount -- 总页数
*/
DROP PROCEDURE
IF EXISTS Query_Pagination;

CREATE PROCEDURE Query_Pagination (
IN _fields VARCHAR (2000),
IN _tables text,
IN _where VARCHAR (2000),
IN _orderby VARCHAR (200),
IN _pageindex INT,
IN _pagesize INT,
IN _sumfields VARCHAR (200),/*增加统计字段*/
OUT _totalcount INT,
OUT _pagecount INT
)
BEGIN

SET @startRow = _pageSize * (_pageIndex - 1);


SET @pageSize = _pageSize;


SET @rowindex = 0;


SET @strsql = CONCAT(
'select sql_calc_found_rows @rowindex:=@rowindex+1 as rownumber,',
_fields,
' from ',
_tables,
CASE ifnull(_where, '')
WHEN '' THEN
''
ELSE
concat(' where ', _where)
END,
' order by ',
_orderby,
' limit ' ,@startRow,
',' ,@pageSize
);

PREPARE strsql
FROM
@strsql;

EXECUTE strsql;

DEALLOCATE PREPARE strsql;


SET _totalcount = found_rows();


IF (_totalcount <= _pageSize) THEN

SET _pagecount = 1;


ELSE

IF (_totalcount % _pageSize > 0) THEN

SET _pagecount = _totalcount / _pageSize + 1;


ELSE

SET _pagecount = _totalcount / _pageSize;


END
IF;


END
IF;


IF (ifnull(_sumfields, '') <> '') THEN

SET @sumsql = contact (
'select ',
_sumfields,
' from ',
_tables,
CASE ifnull(_where, '')
WHEN '' THEN
''
ELSE
concat(' where ', _where)
END
);

PREPARE sumsql
FROM
@sumsql;

EXECUTE sumsql;

DEALLOCATE PREPARE sumsql;


END
IF;


END


set @_totalcount=0;
set @_pagecount=0;
call Query_Pagination ('字段1,字段2......','表名','','id',1,20,'',@_totalcount,@_pagecount);
SELECT @_totalcount;
SELECT @_pagecount;

posted on 2017-08-07 10:58  三人之行,必有我师  阅读(504)  评论(0编辑  收藏  举报