游標是SQL的一個內存工作區
Oracle數據庫的Cursor類型包含三種
create table student(sno number primary key
declare i number:=
beginwhile i<=
loop
insert into student(sno
i:=i+
end loop;
end;
隱式游標屬性
SQL%ROWCOUNT 整型代表DML語句成功執行的數據行數
SQL%FOUND 布爾型值為TRUE代表插入
SQL%NOTFOUND 布爾型與SQL%FOUND屬性返回值相反
SQL%ISOPEN 布爾型DML執行過程中為真
declarebegin update student set sname =
if sql%found then
dbms_output
else
dbms_output
end if;
end;
declare
begin
for names in (select * from student) loop
dbms_output
end loop;
exception when others then
dbms_output
end;
顯式游標屬性
%ROWCOUNT 獲得FETCH語句返回的數據行數
%FOUND 最近的FETCH語句返回一行數據則為真
%NOTFOUND 布爾型 與%FOUND屬性返回值相反
%ISOPEN 布爾型 游標已經打開時值為真
對於顯式游標的運用分為四個步驟
a 定義游標
b 打開游標
c 操作數據
d 關閉游標
典型顯式游標
declare cursor cur_rs is select * from student; sinfo student%rowtype;
begin open cur_rs;
loop
fetch cur_rs into sinfo;
exit when cur_rs%%notfound;
dbms_output
end loop;
exception when others then
dbms_output
end;
帶參數open的顯式cursor:
declare cursor cur_rs(in_name varchar
from student where sname=in_name;
begin for sinfo in cur_rs(
dbms_output
end loop;
exception when others then
dbms_output
end;
使用current of語句執行update或delete操作
declare
cursor cur_rs is select * from student for update;
begin for sinfo in cur_rs loop
update student set sname=sname||
end loop;
commit;
exception when others then
dbms_output
end;
REF游標
也可以利用REF CURSOR實現BULK SQL
REF CURSOR分兩種
Strong REF CURSOR: 指定retrun type
Weak REF CURSOR: 不指定return type
運行時根據動態sql查詢結果遍歷
create or replace package pkg_test
type student_refcursor_type is ref cursor return student%rowtype;
procedure student_rs_loop(cur_rs IN student_refcursor_type)
end pkg_test
create or replace package body pkg_test
procedure student_rs_loop(cur_rs IN student_refcursor_type) is
std student%rowtype;
begin loop
fetch cur_rs into std;
exit when cur_rs%NOTFOUND;
dbms_output
end loop;
end student_rs_loop;
end pkg_test
declare stdRefCur pkg_test
begin for i in
dbms_output
open stdRefCur for select * from student where sno=i;
pkg_test
end loop;
exception when others then dbms_output
close stdRefCur;
end;
使用FORALL和BULK COLLECT子句
create table
student_tmp as select sno
sname from student where
declare cursor cur_std(stdid student
sname from student where sno=stdid;
type student_table_type is table of cur_std%rowtype index by pls_integer;
student_table student_table_type;
begin
open cur_std(
fetch cur_std bulk collect into student_table;
close cur_std;
for i in unt loop
dbms_output
|| student_table(i)
end loop;
forall i in student_table
insert into student_tmp values(student_table(i)
commit;
end;
From:http://tw.wingwit.com/Article/program/Oracle/201311/17358.html