需求:有一系列后缀带有序数字的表,如何利用存储过程循环清空表。
下面是利用了mysql存储过程循环处理的代码。
DROP PROCEDURE ABC;
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
DECLARE a INT Default 0 ;
simple_loop: LOOP
SET a=a+1;
SET @s = CONCAT('DELETE FROM tb_name', convert(a, char));
SET @s2 = CONCAT(@s, ' WHERE id > 1000');
PREPARE stmt3 FROM @s2;
EXECUTE stmt3;
IF a=99 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
call ABC()
利用了CONCAT连接字符串, 利用 PREPARE stmt3 来执行语句
今天拿到另一个类似的需求,要把玩家100-304段的道具遍历的加到200000, 多利用convert拼接了一下。
DROP PROCEDURE ADDPROP;
DELIMITER $$
CREATE PROCEDURE ADDPROP()
BEGIN
DECLARE id INT Default 80052;
DECLARE begin_pid INT Default 100;
DECLARE end_pid INT Default 304;
DECLARE val INT Default 200000;
simple_loop: LOOP
SET begin_pid = begin_pid +1;
SET @s = CONCAT("REPLACE INTO user_properties(id, pid, value) VALUES (", convert(id, char));
SET @ss = CONCAT(@s, ",", convert(begin_pid, char), ",", convert(val, char), ")");
PREPARE final FROM @ss;
EXECUTE final;
IF begin_pid = end_pid THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
call ADDPROP()