mysql 分页查询的存储过程方法

时间:2022-10-19 04:43:53

CREATE DEFINER=`root`@`%` PROCEDURE `pr_pager`(IN p_table_name VARCHAR(4024),IN p_fields VARCHAR(1024), IN p_page_size INT,IN p_page_now INT,IN p_order_string VARCHAR(128),IN p_where_string VARCHAR(4000),in p_only_count bit)
BEGIN
DECLARE m_begin_row INT DEFAULT 0;
DECLARE m_limit_string CHAR(64);

if(p_page_now=0) then
set p_page_now=1;
end if;

SET m_begin_row = (p_page_now - 1) * p_page_size;
SET m_limit_string = CONCAT(' LIMIT ', m_begin_row, ', ', p_page_size);
SET @COUNT_STRING = CONCAT('SELECT COUNT(*) FROM ', p_table_name, ' ', p_where_string);
SET @MAIN_STRING = CONCAT('SELECT ', p_fields, ' FROM ', p_table_name, ' ', p_where_string, ' ', p_order_string, m_limit_string);
if(p_only_count) then

PREPARE count_stmt FROM @COUNT_STRING;
EXECUTE count_stmt;
DEALLOCATE PREPARE count_stmt;
else
PREPARE main_stmt FROM @MAIN_STRING;
EXECUTE main_stmt;
DEALLOCATE PREPARE main_stmt;


end if;

END