游标(Cursor):用来查询数据库,获取记录集合(结果集)的指针,可以让开发者一次访问一行结果集,在每条结果集上作操作。
create or replace procedure TEST is
cursor c1(inname in varchar2) is
select tname from tab where tname like inname;
pname varchar2(32);
begin
open c1('T%');
loop
fetch c1 into pname;
exit when c1%notfound;
dbms_output.put_line(pname);
end loop;
close c1;
end TEST;
declare
begin
update departments set department_name = department_name;
dbms_output.put_line('update ' || sql%rowcount || ' records');
end;
//例子1:无参数,使用循环,无须打开关闭游标
create or replace procedure TEST is
cursor c1 is select tname from tab;
begin
for rr in c1 loop
dbms_output.put_line(rr.tname);
end loop;
end TEST;
//例子2:有参数,使用循环,无须打开关闭游标
create or replace procedure TEST is
cursor c1(inname in varchar2) is select tname from tab where tname like inname;
begin
for rr in c1('T%') loop
dbms_output.put_line(rr.tname);
end loop;
end TEST;
declare /* /* 定义静态游标 */ */
Cursor emps is
Select * from employees where rownum < 6 order by 1;
emp employees%rowtype;
row number := 1;
begin
Open emps; /* ´打开静态游标 */
fetch emps into emp; /* 读取游标当前行 */
loop
if emps%found then
dbms_output.put_line('Looping over record ' || row || ' of ' || emps%rowcount);
fetch emps into emp;
row := row + 1;
elsif emps%notfound then
exit;
end if;
End loop;
If emps%isopen then
close emps; /* 关闭游标 */
End if;
End;
create or replace procedure pc_SetVersionValid(PFlowsID in integer) is
Cursor c1 is
select * from wf_flows
where flowname in
(select flowname from wf_flows where flowsid = PFlowsID)
for update;
r c1%rowtype;
v integer;
begin
open c1;
fetch c1 into r;
while c1%found loop
if r.flowsid = PFlowsID then
v := 1;
else
v := 0;
end if;
UPDATE wf_flows SET isValid = v WHERE CURRENT OF c1;
fetch c1 into r;
end loop;
close c1;
commit;
end;
declare
type my_cur_type is ref cursor;
mycur my_cur_type;--声明引用游标变量
which varchar2(10);
deptrow dept%rowtype;
emprow emp%rowtype;
begin
which := '&请选择dept还是emp';
if (which = 'dept') then
open mycur for select * from dept; --引用游标可以动态sql
loop
fetch mycur into deptrow;
exit when (mycur%notfound);
dbms_output.put_line(deptrow.deptno || ' ' || deptrow.dname);
end loop;
elsif (which = 'emp') then
open mycur for select * from emp; --引用游标可以动态sql
loop
fetch mycur into emprow;
exit when (mycur%notfound);
dbms_output.put_line(emprow.empno || ' ' || emprow.ename);
end loop;
end if;
close mycur;
end;
declare
type mycurtype is ref cursor return emp%rowtype;
mycur mycurtype;--声明变量
emprow emp%rowtype;
begin
open mycur for select * from emp;
loop
fetch mycur into emprow;
exit when mycur%notfound;
dbms_output.put_line(emprow.empno || ' ' || emprow.ename);
end loop;
close mycur;
end;
喜欢 (9)or分享 (0)