游标cursor
SELECT * FROM SCOTT.EMP; --游标cursor:对查询出的结果进行逐行操作的内存指针 --隐式游标:在DML,游标自动(打开,操作,关闭) /* SQL%FOUND 如果有行受影响返回true SQL%NOTFOUND 如果没有行受影响返回true SQL%ROWCOUNT 返回受影响的行数 SQL%ISOPEN 游标是否打开,隐式游标的这个值永远是false */ begin update scott.emp set sal = sal+200 where sal<=800; if SQL%FOUND then dbms_output.put_line('共影响了'||SQL%ROWCOUNT||'行'); else dbms_output.put_line('没有行受影响'); end if; end; --commit; rollback; --显式游标 --游标是和结果集同时出现的,那么在定义显示游标时就要伴随select语句 declare emprow scott.emp%rowtype; cursor cur is select * from scott.emp; --1.定义一个游标带select语句 begin open cur; --2.打开游标 loop fetch cur into emprow; --2.利用循环抓取每一行,放入到emprow; exit when cur%NOTFOUND; -- 直到发现没有结果集了 --3.操作游标抓到的每一行数据 dbms_output.put_line(emprow.empno||' '||emprow.ename); end loop; close cur; --4.关闭游标 end; --带参数的游标:产生游标的 select语句有时需要参数 declare empno scott.emp.empno%type; emprow scott.emp%rowtype; CURSOR cur (eno scott.emp.empno%type)--该游标要传入一个eno的变量 --eno相当于形参 void abc(int eno) is select * from scott.emp where empno=eno; begin empno := '&输入员工的编号'; open cur(empno);--打开游标,记得要传参数 loop fetch cur into emprow ; --用游标抓取数据 exit when cur%notfound; --游标退出 条件 --操作游标指向的行 dbms_output.put_line(emprow.empno||' '||emprow.ename); end loop; end; --显示带参数游标来更新工资:物价上涨,输入员工号,工资涨1.1; declare empno scott.emp.empno%type; emprow scott.emp%rowtype; CURSOR cur (eno scott.emp.empno%type)--该游标要传入一个eno的变量 --eno相当于形参 void abc(int eno) is select * from scott.emp where empno=eno for update of sal;--要更新+for update begin empno := '&输入员工的编号'; open cur(empno);--打开游标,记得要传参数 loop fetch cur into emprow ; --用游标抓取数据 exit when cur%notfound; --游标退出 条件 --操作游标指向的行,涨工资,使用当前游标做为条件 update scott.emp set sal = sal *1.1 where current of cur; end loop; end; select * from scott.emp; --循环游标 declare cursor cur is select empno,ename,sal from scott.emp where deptno='&deptno'; begin for new_cur in cur loop dbms_output.put_line(new_cur.empno|| ' '|| new_cur.ename || new_cur.sal); end loop; end; --ref cursor:动态的产生游标的select语句 declare search_type varchar2(1);--E代表员工表,D代表部门表 type cur is ref cursor; --定义一个ref游标类型 new_cur cur; --1.定义一个ref游标 p_name varchar2(20); begin search_type :='&请输入你要查询的表'; if search_type='E' then open new_cur for select ename name from scott.emp; --2.打开游标 elsif search_type='D' then open new_cur for select dname name from scott.dept; else dbms_output.put_line('输入有误'); end if; loop fetch new_cur into p_name; exit when new_cur%notfound; dbms_output.put_line(p_name); end loop; close new_cur; end;