版权声明: https://blog.csdn.net/aic1999/article/details/82826854
游标
【导言】可以把游标当初我们的鼠标,主要起定位作用,假如我们想要找到表中的特定一行,可以使用游标定位。
【通用结构】
declare
cursor 游标名 is sql语句
begin
open 游标名;
fetch 游标名 into 某变量;
exit when 条件;
close 游标名
end;
【例题1】使用游标输出属于计算机院的学生姓名。
declare
cursor st_cur is select sname from student where deptno=(select deptno from sdept where dname like '%计算机%');
x student.sname%type;
begin
open st_cur;
loop
fetch st_cur into x;
exit when st_cur%notfound;
dbms_output.put_line(x);
end loop;
close st_cur;
end;
【例题2】使用游标输出计算机院学生的姓名和学号,以及总行数。
declare
cursor st_cur is select sno,sname from student where deptno=(select deptno from sdept where dname like '%计算机%');
type rec is record( --也能is table
y student.sno%type, --y student.sno%type;
x student.sname%type --x student.sname%type;
);
m rec;
begin
open st_cur;
loop
fetch st_cur into m; -- fetch st_cur into y,x;
exit when st_cur%notfound;
dbms_output.put_line(m.y||m.x); -- dbms_output.put_line(y||x);
end loop;
dbms_output.put_line(st_cur%rowcount); --输出总行数
close st_cur;
exception
when no_data_found then dbms_output.put_line('no values');
end;
【导言】所以由上可见,查询信息的操作使用游标还不如直接使用for循环遍历呢。那游标有什么优点呢?答:它可以灵活插入修改特定行的数值,如果符合要求,则提交修改,不符合,则回滚,不修改。
【例题3】使用游标操作emp表,为职工涨工资,总裁长30/,经历20/,其他人10/,最后工资总额限制在5W,如果超过,取消。
declare
cursor emp_c is select job from emp for update of sal;
v_job emp.job%type;
v_sal emp.sal%type;
begin
open emp_c;
loop
fetch emp_c into v_job;
exit when emp_c%notfound;
if v_job='president' then
update emp set sal=sal*1.3 where current of emp_c;
elsif v_job='manager' then
update emp set sal=sal*1.2 where current of emp_c;
else
update emp set sal=sal*1.1 where current of emp_c;
end if;
end loop;
select sum(sal) into v_sal from emp;
if v_sal<50000 then
commit; --提交
dbms_output.put_line('ok');
else
rollback; --回滚
dbms_output.put_line('error');
end if;
close emp_c;
end;
【补充】select into\update\delete 使用的时候都会使用到隐式游标。