Oracle (3) 游标的使用

游标 

【导言】可以把游标当初我们的鼠标,主要起定位作用,假如我们想要找到表中的特定一行,可以使用游标定位。

【通用结构】

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 使用的时候都会使用到隐式游标。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值