拆分表 儲存過程
阿新 • • 發佈:2022-05-30
# 計算分割後字串個數函式:func_split_index # 傳入待分割的字串和分割符,返回分割後的字串個數 DELIMITER $$ DROP function IF EXISTS `func_split_index` $$ CREATE FUNCTION `func_split_index` (f_string varchar(1000),f_delimiter varchar(5)) RETURNS int(11) DETERMINISTIC BEGIN return 1+(length(f_string) - length(replace(f_string,f_delimiter,''))); END$$ DELIMITER; # 字串分割函式:func_split_string # 傳入待拆分的字串和分割符,返回拆分後的字串 DELIMITER $$ DROP function IF EXISTS `func_split_string` $$ CREATE FUNCTION `func_split_string` (f_string varchar(1000),f_delimiter varchar(5),f_order int) RETURNS varchar(255) CHARSET utf8 DETERMINISTIC BEGIN declareresult varchar(255) default ''; set result = reverse(substring_index(reverse(substring_index(f_string,f_delimiter,f_order)),f_delimiter,1)); return result; END$$ DELIMITER; # 儲存過程:proc_split # 傳入待拆分的欄位、繫結的id、分割符;構建臨時表,插入已拆分資料 DELIMITER $$ DROP PROCEDURE IF EXISTS `proc_split` $$CREATE PROCEDURE `proc_split` (IN f_string_1 varchar(1000),IN f_string_2 varchar(1000),IN idstr int, IN f_delimiter varchar(5)) BEGIN declare index int default 0; declare i int default 0; set index = func_split_index(f_string_1,f_delimiter); DROP TABLE IF EXISTS `tmp_split`; create temporary table `tmp_split` (`tmp_1` varchar(128) not null,`tmp_2` varchar(128) not null,`ids` int ) DEFAULT CHARSET=utf8; while i < index do set i = i + 1; insert into tmp_split(`tmp_1`,`tmp_2`,`ids`) values (func_split_string(f_string_1,f_delimiter,i),func_split_string(f_string_2,f_delimiter,i),idstr); end while; END$$ DELIMITER; # 根據臨時表拆分結果插入資料 DELIMITER $$ DROP PROCEDURE IF EXISTS `proc_tab_insert` $$ CREATE PROCEDURE `proc_tab_insert` () BEGIN declare orderId varchar(500) default '' ; declare orderNum varchar(500) default '' ; declare requestId int default 0; declare tmpName varchar(100) default '' ; -- 定義遊標 declare cur1 CURSOR FOR SELECT order_id FROM dfs_purchase_request ; declare cur2 CURSOR FOR SELECT order_num FROM dfs_purchase_request ; declare cur3 CURSOR FOR SELECT id FROM dfs_purchase_request; -- 定義迴圈結束條件 declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tmpName = null; -- 開遊標 OPEN cur1 ; OPEN cur2 ; OPEN cur3 ; FETCH cur1 INTO orderId; FETCH cur2 INTO orderNum; FETCH cur3 INTO requestId; -- 清空待插入的表 -- TRUNCATE dfs_purchase_request_order_relation; WHILE ( tmpName is not null) DO call proc_split(orderId,orderNum,requestId,","); INSERT INTO dfs_purchase_request_order_relation (order_id,order_num,request_id) SELECT tmp_1,tmp_2,ids from tmp_split; FETCH cur1 INTO orderId; FETCH cur2 INTO orderNum; FETCH cur3 INTO requestId; END WHILE; -- 關閉遊標 CLOSE cur1; CLOSE cur2; CLOSE cur3; -- 查詢插入結果 select * from dfs_purchase_request_order_relation; END$$ DELIMITER; call proc_tab_insert();