ORACLE動態游標實戰舉例

2021-07-09 23:03:56 字數 2790 閱讀 9476

游標是資料庫程式設計中必須要熟練掌握的技術,主要實現針對資料集合,進行迴圈處理,因為sql本身只能一次性處理,所以當有稍微複雜的因為時,都在儲存過程中使用游標進行實現。靜態游標在執行前就能確定對應查詢語句,最多只是傳遞一些查詢引數而已,所以比較容易處理。動態游標是在執行前查詢sql是動態拼接的,不確定具體查詢那些表和條件。

在mssql中,定義動態游標比較麻煩,一般先拼接sql,然後動態執行存放臨時表中,然後定義游標讀取臨時表;相比oracle則強大多了,直接定義游標,然後直接開啟就可以實現,感慨其強大。下面通過示例進行說明。

1、靜態游標示例

create or replace

procedure px_varify_zrp_repeat

( v_import_id in varchar2

) as

v_person_id varchar2(36); -- 返回主體id

v_cnt number(5,0); -- 符合條件記錄數

cursor cv_persons is

select id,id_type,id_code from nat_person_info

where import_id = v_import_id;

begin

for cv_person in cv_persons loop

px_varify_zrp_ids_atom(cv_person.id_type,cv_person.id_code,v_person_id,v_cnt); -- 執行其他過程,實現複雜業務

if v_cnt = 0 and v_person_id is null then

update nat_person_info set import_check_flag = '0' , check_err_msg = check_err_msg || ' 驗證規則**:1001;錯誤描述:未找到對應自然人資訊.'

where id = cv_person.id;

end if;

end loop;

end px_varify_zrp_repeat;

2、動態游標示例

動態sql作為游標執行的語句,定義時僅說明型別,開啟時指定sql.迴圈處理是採用loop,所以需要手動結束。

create or replace

procedure px_varify_zrp_ext_match

( v_table_name in varchar2

, v_import_id in varchar2

) as

v_sql varchar2(1024);

vu_sql varchar2(1024);

type cv_persons is ref cursor;

cv_person cv_persons;

v_id nat_person_info.id%type; -- id

v_id_type nat_person_info.id_type%type; -- 證件型別

v_id_code nat_person_info.id_code%type; -- 證件號碼

v_person_id varchar2(36); -- 返回主體id

v_cnt number(5,0); -- 符合條件記錄數

begin

v_sql := 'select id,id_type,id_code ';

v_sql := v_sql || ' from ' || v_table_name;

v_sql := v_sql || ' where import_id = ' || v_import_id;

open cv_person for v_sql;

loop

fetch cv_person into v_id,v_id_type,v_id_code;

exit when cv_person%notfound;

px_varify_zrp_ids_atom(v_id_type,v_id_code,v_person_id,v_cnt);

if v_cnt = 1 and v_person_id is not null then

vu_sql := 'update ' || v_table_name || ' set person_id = ''' || v_person_id || ''' where id = ''' || v_id || '''' ;

end if;

if v_cnt = 0 and v_person_id is null then

vu_sql := 'update ' || v_table_name || ' set import_check_flag = ''0'' , ' ;

vu_sql := vu_sql || ' check_err_msg = check_err_msg || ' || ''' 驗證規則**:1001;錯誤描述:未找到對應自然人資訊.''';

vu_sql := vu_sql || ' where id = ''' || v_id || '''' ;

end if;

dbms_output.put_line(vu_sql);

execute immediate vu_sql;

end loop;close cv_person;

end px_varify_zrp_ext_match;

Oracle游標舉例

游標 顯式游標 顯式游標的使用方式 4個步驟 定義游標 語法 cursor 游標名 is 查詢子句 開啟游標 語法 open 游標名 獲取結果 遍歷游標 語法 fetch 游標名 into 變數 關閉游標 語法 close 游標名 declare cursor cur stu is select f...

oracle動態游標

declare v col1 varchar2 254 v col2 varchar2 254 v sql varchar2 1024 type my cursor is ref cursor v cur my cursor begin v sql select 1,2 from dual wher...

oracle 動態游標

今天寫了個動態游標 使用傳入引數 關於游標分類以及用法 思路就是先拼好sql 然後開動態游標 oralce10g也支援正規表示式 呵呵 剛剛好可以實現動態傳入引數 procedure tj pda testdata v indicator in varchar is type rc is ref c...