Oracle学习笔记——在PL/SQL使用游标获取数据

来源:互联网 发布:c语言定义变量 编辑:程序博客网 时间:2024/06/05 03:58

oracle不允许定义数组,查找出来的数据是一个大集合的话就需要使用游标进行遍历打印


隐式游标

例子:遍历emp表中员工,打印员工的名字和薪水

declare-- 静态游标 游标指向结果集                                                                        cursor test_cursor is  select * from emp;row_info emp%rowtype;begin -- 打开游标 open test_cursor;    loop       fetch  test_cursor into row_info; -- 赋值            exit when test_cursor%notfound;      dbms_output.put_line(row_info.ename|| row_info.sal);    end loop;  close test_cursor;end;

结果:



例子二;

/* 查询员工表中 工资 超过4000 的员工 信息, 如果他所在的是市场部门,那么他的工资减少10%;*/declare  cursor  info_cursor is select empno,sal,dname from emp,dept where emp.deptno = dept.deptno; v_empno number(4); v_sal number(7,2); v_dname varchar2(50);begin  open info_cursor;  loop    fetch info_cursor into v_empno,v_sal,v_dname;    exit when info_cursor%notfound;    if v_sal>4000 and v_dname='ACCOUNTING' then        update emp set sal =sal-sal*0.1 where empno = v_empno;        commit;    end if;  end loop;  close info_cursor;end;

动态游标

-- 动态游标declare-- 声明一个 引用游标 type cursor_type is ref cursor; -- 声明引用游标变量  emp_cursor cursor_type;  emp_info emp%rowtype;begin-- 打开游标 并 指向sql   open emp_cursor for select * from emp;    loop      fetch  emp_cursor into emp_info;      exit when emp_cursor%notfound;      dbms_output.put_line(emp_info.ename);   end loop;   close emp_cursor;end;

效果:






原创粉丝点击