游標是一種PL/SQL控制結構
顯示游標: Declared and named by the programmer
隱式游標: Declared for all DML and PL/SQL SELECT statements
%FOUND
%NOTFOUND
%ISOPEN
%ROWCOUNT
注意
if b then
dbms_output
end if;
或者
declare
b boolean;
begin
b := true;
dbms_output
end;
對於null
顯示游標:需要手動open和close
例如
DECLARE
CURSOR mycursor IS
SELECT * FROM dept;
myrecord dept%ROWTYPE;
BEGIN
OPEN mycursor;
FETCH mycursor INTO myrecord;
WHILE mycursor%FOUND LOOP
DBMS_OUTPUT
FETCH mycursor INTO myrecord;
END LOOP;
CLOSE mycursor;
END;
注意
帶參數的游標
DECLARE
CURSOR mycursor(num varchar
SELECT * FROM DEPT WHERE deptno=num;
myrecord dept%ROWTYPE;
BEGIN
OPEN mycursor(
LOOP
FETCH mycursor INTO myrecord;
EXIT WHEN mycursor%NOTFOUND;
DBMS_OUTPUT
END LOOP;
CLOSE mycursor;
END;
FOR循環操作游標
使用FOR循環讀取游標時
DECLARE
CURSOR mycursor(num varchar
SELECT * FROM DEPT WHERE deptno=num;
BEGIN
FOR cur IN mycursor(
DBMS_OUTPUT
END LOOP;
END;
注意
當直接將游標的值讀取到變量時
DECLARE
d_no number;
d_name varchar
CURSOR mycursor(num varchar
SELECT deptno
BEGIN
OPEN mycursor(
FETCH mycursor INTO d_no
LOOP
DBMS_OUTPUT
FETCH mycursor INTO d_no
EXIT WHEN mycursor%NOTFOUND;
END LOOP;
CLOSE mycursor;
END;
/
%ROWCOUNT初始值為null
例如
DECLARE
d_name varchar
CURSOR mycursor IS
SELECT dname FROM DEPT;
BEGIN
OPEN mycursor;
LOOP
FETCH mycursor INTO d_name;
EXIT WHEN mycursor%NOTFOUND;
DBMS_OUTPUT
END LOOP;
CLOSE mycursor;
END;
結果集中有
可更新數據的游標
要想在使用游標的同時修改數據
例如
DECLARE
d_name VARCHAR
CURSOR mycursor IS
SELECT dname FROM dept FOR UPDATE;
BEGIN
OPEN mycursor;
LOOP
FETCH mycursor INTO d_name;
EXIT WHEN mycursor%NOTFOUND;
UPDATE dept SET dname=RTRIM(dname
END LOOP;
CLOSE mycursor;
END;
CURRENT OF+游標名
RTRIM(dname
隱式游標
例如
BEGIN
FOR cur IN(SELECT dname FROM dept) LOOP
DBMS_OUTPUT
END LOOP;
END;
declare
cursor cur_my (mv number) is select * from Person where no<mv;
begin
for tem in cur_my(
DBMS_OUTPUT
end loop;
end;
declare
temp_row Person%rowtype;
type my_type is ref cursor;
cur_my my_type;
begin
open cur_my for
loop
fetch cur_my into temp_row;
exit when cur_my%notfound;
DBMS_OUTPUT
end loop;
close cur_my;
end;
DECLARE
v_id Integer;
v_name varchar
v_age Integer;
cursor cur_mycursor is select id
BEGIN
for temp in cur_mycursor loop
v_id :=temp
v_name :=temp
v_age :=temp
dbms_output
end loop;
/**dbms_output
END;
DECLARE
v_id Integer;
v_name varchar
v_age Integer;
cursor cur_mycursors is select id
BEGIN
OPEN cur_mycursors;
dbms_output
LOOP
FETCH cur_mycursors INTO v_id
dbms_output
IF cur_mycursors%NOTFOUND THEN
EXIT;
END IF;
END LOOP;
dbms_output
CLOSE cur_mycursors;
END;
From:http://tw.wingwit.com/Article/program/Oracle/201311/19107.html