Oracle迴圈插入儲存過程轉Mysql經驗積累

2021-10-11 19:12:26 字數 2120 閱讀 4407

oracle迴圈插入儲存過程:

--oracle的入參可自定義object types 為陣列型別

create or replace procedure "test_pro"(newarray in msg_array)

asdatacount number(10):=newarray.count/2;--取迴圈次數,因業務需求是傳入的陣列id,奇數字置為需插入old_id的資料,偶數字置為已經存在的old_id資料,所以只需要迴圈陣列長度的一半

begin

for i in 1 .. datacount loop

insert into t_batch_data select sys_guid() as id, newarray(2*i-1) as old_id, remark from t_batch_data where old_id=newarray(2*i);

end loop;

commit;

exception

when others then

rollback;

end;

改造後mysql:

--mysql不存在自定義型別,所以這裡只能協商好傳入引數的格式,以逗號分隔id,為後面切割獲取id準備

create procedure `test_pro`(in msg_array varchar(4000))

begin

declare object1_id varchar(500);--奇數字置的id

declare object2_id varchar(500);--偶數字置的id

declare i int;--msg_array左邊第一次出現逗號的位置

declare len int;--msg_array存在id的個數

set len = (select length( msg_array) - length(replace(msg_array,',','' ))) + 1;--根據逗號計算出id的個數

--msg_array不能為空

if (msg_array is not null) or (ltrim(msg_array) != '') then

--迴圈id個數

mywhile: while len > 0 do

--id個數為奇數時不作處理,len長度減一

if (len % 2) != 0 then

set len = len - 1;

--這裡相當於continue,繼續迴圈的意思

iterate mywhile;

else

--取逗號從左往右第一次出現的位置

set i = locate(',', msg_array);

--根據逗號位置截取出第乙個id

set object1_id = left(msg_array, i-1);

--msg_array重新賦值為去掉第乙個id後的字串

set msg_array = right(msg_array,length(msg_array)-i);

--取第二個id時重複上面的操作

set i = locate(',', msg_array);

--取最後乙個時是不存在逗號了的。所以直接把msg_array的值賦給object2_id就行了

if i = 0 then

set object2_id = msg_array;

else

set object2_id = left(msg_array, i-1);

set msg_array = right(msg_array,length(msg_array)-i);

end if;

--獲取到奇數字和偶數字的id就可以進行插入了

insert into t_batch_data select uuid(),object1_id,remark from t_batch_data where old_id=object2_id;

--迴圈後記得長度減一

set len = len - 1;

end if;

--結束迴圈

end while mywhile;

end if;

end

oracle儲存過程迴圈操作

create or replace procedure test procedure is begin 迴圈列印1到5 for idx in 1.5 loop dbms output.put line idx end loop 根據查詢到的資料進行遍歷並輸出 for idx in select t....

MySQL 利用儲存過程while迴圈插入資料

個人學習的時候通常需要創造一些測試資料,一般是利用儲存過程。例如向test表中插入大量資料 create table test id int 11 not null auto increment,name varchar 10 default null,primary key id 定義語句結束符為...

mysql 儲存過程按日期迴圈插入

參考部落格 定義與使用變數時需要注意以下幾點 1 declare語句必須用在degin end語句塊中,並且必須出現在degin end語句塊的最前面,即出現在其他語句之前。2 declare定義的變數的作用範圍僅限於declare語句所在的degin end塊內及巢狀在該塊內的其他degin en...