oracle笔记六(游标)
游标:游标是一个指向上下文的句柄( handle)或指针
1. 显示游标(用于查询语句,尤其是多行的查询语句)
Declare
V_emp emp%rowtype;
Cursor c_cursor is select * from emp;
Begin
Open c_cursor;
Fetch c_cursor into v_emp;
While c_cursor%found loop
dbms_output.put_line(v_record.empno ||','||v_record.ename||','||v_record.sal);
Fetch c_cursor into v_emp;
End loop;
Close c_cursor;
End;
2. 带参游标
Declare
V_emp emp%rowtype;
Cursor c_cursor(p_deptno emp.deptno%type) is select * from emp where deptno=p_deptno;
Begin
Open c_cursor(20);
Fetch c_cursor into v_emp;
While c_cursor%found loop
dbms_output.put_line(v_record.empno ||','||v_record.ename||','||v_record.sal);
Fetch c_cursor into v_emp;
End loop;
Close c_cursor;
End;
4. 游标属性
a).%found
b).%notfound
c).%isopen(隐式游标中永远为false)
d).%rowcount
5. 隐式游标(主要用于DML操作)
declare
v_deptno emp.DEPTNO%type:=&deptno;
begin
delete from emp where deptno=v_deptno;
if sql%notfound then
delete from dept where deptno=v_deptno;
commit;
else rollback;
end if;
end;
6. 显示游标的FOR循环
Declare
Cursor c_cursor is select * from emp;
Begin
--隐含打开游标
For emp_record in c_cursor loop
--隐含执行一个FETCH语句
If emp_record.sal <1200 then
Update emp set sal=sal+100 where empno=emp_record.empno;
dbms_output.put_line(emp_record.empno ||'sal updated');
end if;
--隐含监测c_cursor%NOTFOUND
end loop;
--隐含关闭游标
End;
7. NO_DATA_FOUND 和 %NOTFOUND的区别
a).SELECT … INTO 语句触发 NO_DATA_FOUND
b).当一个显式游标的WHERE子句未找到时触发%NOTFOUND;
c).当UPDATE或DELETE 语句的WHERE 子句未找到时触发 SQL%NOTFOUND;
d).在提取循环中要用 %NOTFOUND 或%FOUND 来确定循环的退出条件,不要用 NO_DATA_FOUND.
8. 游标修改和删除操作
declare
cursor c_cursor(p_deptno dept.DEPTNO%type default 10) is
select * from emp where deptno=p_deptno
for update nowait;
begin
for c_ces in c_cursor(60) loop
if c_ces.sal<1500 then
update emp set sal=1500 where current of c_cursor;
dbms_output.put_line(c_ces.ename || 'salary is updated');
end if;
end loop;
--dbms_output.put_line(c_cursor%rowcount);
end;