1、匿名塊的格式基本就如下面所示
[declare]
/*變量定義區(qū),也可做初使化等*/
begin
/*開(kāi)始區(qū),執(zhí)行順序SQL語(yǔ)句*/
[exception]
/*異常處理區(qū),可進(jìn)行異常處理,異常的拋出使用raise關(guān)鍵字*/
end;
其中方框里面的為可選項(xiàng),不作為必須。
2、
fetch
1)首先要定義
cursor,如
cursor id_cur is select id from components
2)然后打開(kāi)
cursor:open id_cur
3)第三是使用
fetch從
cursor并保存到變理中
4)第四關(guān)閉
cursor
那就把上面說(shuō)到的功能實(shí)現(xiàn),代碼如下:
- declare
- num_id integer;/*定義變量*/
- sql_str varchar(1000);
- cursor id_cur is select id from components;/*用光標(biāo)取ID*/
- begin
- open id_cur;/*打開(kāi)光標(biāo)執(zhí)行*/
- loop/*一直執(zhí)行下去*/
- fetch id_cur into num_id;/*根據(jù)光標(biāo),取出ID號(hào)到變量中*/
- exit when id_cur%notfound;/*沒(méi)有記錄時(shí)就退出*/
- if mod(num_id,5)=0 then/*如果記錄ID為5的倍數(shù),就執(zhí)行下面的插入*/
- /*下面生成一條SQL語(yǔ)句*/
- sql_str:='insert into components2 select * from components where id='|| num_id;
- /*立即執(zhí)行生成的SQL語(yǔ)句*/
- execute immediate sql_str;
- end if;/*記住:條件的結(jié)束后都要加結(jié)束束‘;’*/
- end loop;
- close id_cur;/*關(guān)閉光標(biāo)*/
- end;
- /