oracle遊標的更新與刪除數據

通過使用顯示遊標,不僅可以一行一行地處理SELECT語句的結果,而且也可以更新或刪除當前遊標行的數據。注意,如果要通過遊標更新或刪除數據,在定義遊標時必須要帶有FOR UPDATE 子句,語法如下:

cursor cursor_name is select ...for update;

在提取了遊標數據之後,爲了更新或刪除當前遊標行數據,必須在update或delete語句中引用where current of子句,語法如下:

update table_name set column=...where current of cursor_name;

delete table_name where current of cursor_name;

1.使用遊標更新數據

下面以給工資低於2000的僱員增加100元工資爲例,說明使用顯示遊標更新數據的方法。示例如下:
declare
cursor emp_cursor is 
select ename,sal from emp for update;
v_ename emp.ename%type;--定義變量
v_sal emp.sal%type;
begin
open emp_cursor;--打開遊標
loop
fetch emp_cursor into v_ename,v_sal;--提取遊標數據賦值給變量
exit when emp_cursor%notfound;
if v_sal <2000 then --當變量v_sal 小於2000時執行更新操作
update emp set sal=sal+100 where currentof emp_cursor;
end if ;
end loop;
close emp_cursor;--關閉遊標
end;

2.使用遊標刪除數據

下面以解僱部門號爲30的所有僱員爲例,說明使用顯示遊標刪除數據的方法,示例如下:
declare
cursor emp_cursor is 
select ename,sal ,deptno from emp for update;
v_ename emp.ename%type;--定義變量
v_sal emp.sal%type;
v_deptno emp.deptno%type;
begin
open emp_cursor;--打開遊標
loop
fetch emp_cursor into v_ename,v_sal,v_deptno;--提取遊標數據賦值給變量
exit when emp_cursor%notfound;
if v_deptno =30 then --當變量v_deptno等於30時執行刪除操作
delete from  emp where current  of emp_cursor;
end if ;
end loop;
close emp_cursor;--關閉遊標
end;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章