-- declare
-- this cursor is get table employee's info
cursor cur_employee is
select * from employee;
-- this curso is get table dept's info
cursor cur_dept is
select * from dept;
-- this cursor is get table employee & dept info
cursor cur_info is
select e.*, d.dept_name
from employee e , dept d
where e.dept_no = d.dept_no(+);
-- to save cursor record's value
v_employee_row employee%rowtype;
v_dept_row dept%rowtype;
-- for .. loop
for v_row in cur_employee loop
-- TODO-A
end loop;
-- TODO-B
-- open ..close
open cur_employee
fetch cur_employee into v_employee_row;
close cur_table_test;
1.使用For..Loop的方式讀取cursor,open、fetch、close都是隱式打開的。所以,大家不用擔心忘記關閉游標而造成性能上的問題。
2.使用For..Loop的代碼,代碼更加干凈、簡潔,而且,效率更高。
3.使用For..Loop讀取游標后,存儲記錄的變量不需要定義,而且,可以自動匹配類型。假如讀取多個表的記錄,顯然用Open的fetch..into就顯得相當困難了。
fetch cur_info into X (這里的就相當麻煩,而且,隨著涉及的表、字段的增加更加困難)
4.For..Loop在使用游標的屬性也有麻煩的地方。因為記錄是在循環內隱含定義的,所以,不能在循環之外查看游標屬性。
假設要做這樣的處理:當游標為空時,拋出異常。你可以把下面的讀取游標屬性的代碼:
if cur_employee%notfound then
-- can not found record form cursor
RAISE_application_ERROR(error_code, error_content);
end if;
放在<< TODO-B >>的位置,雖然編譯可以通過,但在運行時,它會出現報錯:ORA-01001:invalid cursor。
放在<< TODO-A>>的位置,讀取游標的notfound屬性。顯然,這是行不通的。理由如下:如果游標為空,就會直接跳出循環,根本不會執行循環體內的代碼。但是,也并不代表,我們就不能使用For..Loop來處理了。大家可以通過設置標志字段處理。
定義變量:v_not_contain_data bollean default true;
在For..Loop循環內增加一行代碼:v_not_contain_data := false;
這樣,在循環體外我們可以通過標志位來進行判斷:
If v_not_contain_data then
RAISE_APPLICATION_ERROR(error_code, error_content);
end if;
新聞熱點
疑難解答