Oracle學習筆記(通過游標操縱資料庫)

2021-03-31 17:34:36 字數 2256 閱讀 9443

不是原創哦

來自天極網

在游標for迴圈中使用查詢

在游標for迴圈中可以定義查詢,由於沒有顯式宣告所以游標沒有名字,記錄名通過游標查詢來定義。

decalre

v_tot_salary emp.salary%type;

begin

for r_dept in (select deptno,dname from dept order by deptno) loop

dbms_output.put_line('department:'|| r_dept.deptno||'-'||r_dept.dname);

v_tot_salary:=0;

for r_emp in (select ename,salary

from emp

where deptno=p_dept

order by ename) loop

dbms_output.put_line('name:'|| v_ename||' salary:'||v_salary);

v_tot_salary:=v_tot_salary+v_salary;

end loop;

dbms_output.put_line('toltal salary for dept:'|| v_tot_salary);

end loop;

end;

游標中的子查詢

語法如下:

cursor c1 is select * from emp

where deptno not in (select deptno

from dept

where dname!='accounting');

可以看出與sql中的子查詢沒有什麼區別。

游標中的更新和刪除

在pl/sql中依然可以使用update和delete語句更新或刪除資料行。顯式游標只有在需要獲得多行資料的情況下使用。pl/sql提供了僅僅使用游標就可以執行刪除或更新記錄的方法。

update或delete語句中的where current of子串專門處理要執行update或delete操作的表中取出的最近的資料。要使用這個方法,在宣告游標時必須使用for update子串,當對話使用for update子串開啟乙個游標時,所有返回集中的資料行都將處於行級(row-level)獨佔式鎖定,其他物件只能查詢這些資料行,不能進行update、delete或select...for update操作。

語法:for update [of [schema.]table.column[,[schema.]table.column]..

[nowait]

在多表查詢中,使用of子句來鎖定特定的表,如果忽略了of子句,那麼所有表中選擇的資料行都將被鎖定。如果這些資料行已經被其他會話鎖定,那麼正常情況下oracle將等待,直到資料行解鎖。

在update和delete中使用where current of子串的語法如下:

where

例:delcare

cursor c1 is select empno,salary

from emp

where ***m is null

for update of ***m;

v_***m number(10,2);

begin

for r1 in c1 loop

if r1.salary<500 then

v_***m:=r1.salary*0.25;

elseif r1.salary<1000 then

v_***m:=r1.salary*0.20;

elseif r1.salary<3000 then

v_***m:=r1.salary*0.15;

else

v_***m:=r1.salary*0.12;

end if;

update emp;

set ***m=v_***m

where current of c1l;

end loop;

end

通過從游標工作區中抽取出來的資料,可以對資料庫中的資料進行操縱,包括修改與刪除操作。

要想通過游標操縱資料庫,在定義游標的時候,必須加上for update of子句;

而且在update或delete時,必須加上where current of子句,則游標所在行被更新或者刪除。

乙個for update子句將使所在行獲得乙個行級排他鎖。

Oracle游標學習筆記

游標按以下操作進行 parse 解析 bind 繫結 open 開啟 execute 執行 fetch 回取 close 關閉 1.寫自己第乙個游標pl sql declare cursor c s is select from user tables begin open c s 開啟游標 clo...

oracle學習筆記(五)游標

游標在資料庫操作中有著十分重要的作用,它簡單地說就相當於指標,針對表中檢索出來的結果進行操作,游標分為顯示游標和隱式游標。顯示游標是使用者可以自己宣告和操作的,通常用於操作查詢結果集。通過他來處理資料主要分為四步驟,首先是宣告游標,其次是開啟游標,然後讀取游標,最後關閉游標。1.宣告游標必須指定名稱...

oracle游標筆記

游標 cursor 也叫游標,在關聯式資料庫中經常使用,在pl sql程式中可以用cursor與select一起對錶或者檢視中的資料進行查詢並逐行讀取。oracle游標分為顯示游標和隱式游標。顯示游標 explicit cursor 在pl sql程式中定義的 用於查詢的游標稱作顯示游標。隱式游標 ...