MySQL存儲過程舉例
涉及循環、動態sql等主要的MySQL存儲過程知識。
需求:
遍歷所有【test_ondev_[0-9]】開頭的表,將其中的所有數據按表中的col字段存儲到【test_ondev_history_ + col的值】的表裏面,當【test_ondev_history_ + col】不存在的時候複製test_ondev_history的結構創建該表,並將數據存儲進表裡。
程序思路:
- 遍歷表名
- 將每張表的col字段的內容統計出來
- 創建 test_ondev_history_ + col 的表
- 將數據插入進去test_ondev_history_ + col表中
- 繼續遍歷其他表
使用存儲過程實現:
DELIMITER $$ CREATE PROCEDURE `p_copy_data`() BEGIN DECLARE i INT; DECLARE v_sql_col VARCHAR(200); DECLARE j INT; DECLARE max_id_s INT; DECLARE max_id INT; DECLARE v_tbname VARCHAR(50); DECLARE v_tbname_s VARCHAR(50); DECLARE v_col VARCHAR(50); DECLARE v_sql_create VARCHAR(200); DECLARE v_sql_insert VARCHAR(200); CREATE TABLE IF NOT EXISTS temp_col(id INT PRIMARY KEY AUTO_INCREMENT,col VARCHAR(50)); CREATE TABLE IF NOT EXISTS tbnames(id INT PRIMARY KEY AUTO_INCREMENT,tbname VARCHAR(50)); TRUNCATE TABLE tbnames; INSERT INTO tbnames(tbname) SELECT table_name FROM information_schema.`TABLES` WHERE table_name REGEXP 'test_ondev_[0-9]'; SET i = (SELECT MIN(id) FROM tbnames); SET max_id_s = (SELECT MAX(id) FROM tbnames); WHILE i <=max_id_s DO TRUNCATE TABLE temp_col; SET v_tbname_s = (SELECT tbname FROM tbnames WHERE id = i); SET v_sql_col = CONCAT('insert into temp_col(col) select distinct col from ',v_tbname_s); SET @v_sql_col := v_sql_col; PREPARE stmt FROM @v_sql_col; EXECUTE stmt ; DEALLOCATE PREPARE stmt; SET j =1; SET max_id = (SELECT MAX(id) FROM temp_col ); WHILE j <= max_id DO SET v_col = (SELECT col FROM temp_col WHERE id =j); SET v_tbname = CONCAT('test_ondev_history_',v_col ); SET v_sql_create = CONCAT('create table if not exists ',v_tbname,' like test_ondev_history;'); SET @v_sql_create := v_sql_create; PREPARE stmt FROM @v_sql_create; EXECUTE stmt ; DEALLOCATE PREPARE stmt; SET v_sql_insert = CONCAT('insert into ',v_tbname,' select * from ',v_tbname_s," where col='", v_col ,"';"); SET @v_sql_insert := v_sql_insert; PREPARE stmt FROM @v_sql_insert; EXECUTE stmt ; DEALLOCATE PREPARE stmt; SET j = j + 1; END WHILE; SET i = i + 1; END WHILE; END$$
TIPS:
MySQL不建議使用存儲過程,如果臨時用的話可以考慮臨時使用。
另外,該過程是第一版實現歷史數據的遷移,如果需要重複執行還有不少優化空間,例如:
- 遍歷表的時候需要指定對應庫;
- 上述過程不能重複執行,如果重複執行,需要怎麼改進;
- 中途涉及創建表,如果不創建哪些臨時表改如何調整;
這些就留給大家思考了,也歡迎來和我溝通。文章如果有誤,歡迎斧正 ,非常感謝。