Dynamic sql in Mysql

Mysql中的Dynamic sql,类似于oracle中的Execute immediately语法,写法上稍微麻烦一点,下面是一个具体的例子。

DROP PROCEDURE IF EXISTS total_num;

CREATE PROCEDURE total_num(
IN p_begin INT,
IN p_end INT
)  
BEGIN  
    DECLARE v_begin INT DEFAULT 0;
    DECLARE v_end INT DEFAULT 0;
    DECLARE v_total INT DEFAULT 0;
    
    SET v_begin = p_begin;
    SET v_end = p_end;
    
    WHILE v_begin<=v_end DO 
      SET @sql = CONCAT('SELECT COUNT(1) INTO @item_count FROM t', v_begin);

      PREPARE stmt FROM @sql;
      EXECUTE stmt;
      SET v_total = v_total + @item_count;

      SET v_begin = v_begin+1;
    END WHILE;
    DEALLOCATE PREPARE stmt;

    SELECT v_total;
END

调用方式:

call total_num(1,2)
    原文作者:邢爱明
    原文地址: https://segmentfault.com/a/1190000010470913
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞