mysql 分页存储过程

阅读更多

mysql中的分页通用存储过程,7个参数

p_table_name    表名

p_filelds    取的字段,可以用*

p_page_size    每页的记录数

p_page_now    当前页

p_order_string    排序的字段

p_where_string    检索条件

p_out_rows    符合条件的总记录数

 

 

DROP PROCEDURE IF EXISTS pr_pager;
CREATE PROCEDURE pr_pager(

    IN    p_table_name        VARCHAR(1024),       
    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(1024),      
    OUT    p_out_rows            INT     
    
)
    NOT DETERMINISTIC
    SQL SECURITY DEFINER
    COMMENT '分页存储过程'
    
BEGIN

    /*定义变量*/
    DECLARE m_begin_row INT DEFAULT 0;
    DECLARE m_limit_string CHAR(64);

    /*构造语句*/    
    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(*) INTO @ROWS_TOTAL 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);

    /*预处理*/
    PREPARE count_stmt FROM @COUNT_STRING;
    EXECUTE count_stmt;
    DEALLOCATE PREPARE count_stmt;
    SET p_out_rows = @ROWS_TOTAL;

    PREPARE main_stmt FROM @MAIN_STRING;
    EXECUTE main_stmt;
    DEALLOCATE PREPARE main_stmt;
    
END

 

 

你可能感兴趣的:(mysql分页存储过程,分页)