declare
--声明游标: Cursor is select xxx ; 在没有open之前 不会执行该select语句
Cursor c_emp is
select * from emp where deptno = 10 or deptno = 20;
v_emp emp%rowtype; --声明变量,用来接收从cursor中的取出的每一条数据
begin
open c_emp; --打开cursor ,开始执行select 语句
loop --循环读取cursor结果
fetch c_emp into v_emp; --从结果集中取数据到v_emp变量,并移动指向数据的指针
if c_emp%FOUND --如果上一个fetch找到记录 就返回true .
then dbms_output.put_line(v_emp.ename);
else
EXIT;
end if;
end loop;
close c_emp; --关闭close,释放资源
end;
--2.record类型 + while处理cursor
declare
-- 定义record类型
type r_emp_rec is record(
eid emp.empno%type, name emp.ename%type
);
Cursor c_emp_cursor is
select empno , ename from emp where empno = 7900;
v_emp r_emp_rec;--声明 v_emp 记录类型的变量
begin
open c_emp_cursor;
--必须先fetch,c_emp_cursor%found的值才会是true或false,
- --若不fetch, c_emp_cursor%found的值为null
fetch c_emp_cursor into v_emp;
--通过循环处理结果集中的数据,若c_emp_cursor%Found的值为false,循环结束
while c_emp_cursor%FOUND LOOP
dbms_output.put_line(v_emp.name);
fetch c_emp_cursor into v_emp; --再次fetch
end loop;
close c_emp_cursor;
end;
/
-- 3 . record类型 + for处理cursor +游标参数
-- ----For循环对cursor的处理进行了集成,
------ 不需要open、循环处理fetch、close。cursor中的数据通过for循环中的记录类型的变量emp执行引用。
declare
-- type t_emp_rec is record(
-- salary emp.sal%type, name emp.ename%type
-- );
-- v_emp t_emp_rec;
Cursor c_emp(emp_id number) is -- emp_id是参数
select sal , ename from emp where empno = emp_id;
begin
for emp in c_emp(7900) LOOP
dbms_output.put_line(emp.ename);
end LOOP;
end ;
/
--===========总结==============
--cursor的声明
----1.在游标声明中使用标准的select 语句
----2.查询中可以用order by来处理次序问题。
----3.可以在查询中引用变量,但必须在cursor语句之前声明这些变量.
Cursor c_emp_id(emp_id number) is
select id from service where cost_id = emp_id;
--===========练习=================
-- 打印每个员工的ename , id ,不存在则打印not exists;
declare
Cursor c_emp is
--select * from emp where 1 = 2; -- 模拟没有查询到记录
select * from emp where 1 = 1;
v_emp emp%rowtype;
begin
open c_emp;
fetch c_emp into v_emp;
if c_emp%FOUND
then
while c_emp%FOUND LOOP
dbms_output.put_line(v_emp.ename ||'--------------'|| v_emp.deptno);
fetch c_emp into v_emp;
exit when c_emp%NOTFOUND;
end loop;
else
dbms_output.put_line('not exists');
end if;
close c_emp;
end;
/