显示游标(传参、更新行)

发布时间 2023-04-12 11:56:48作者: Argitacos

--将emp表中奖金为空的数据改为0(显示游标更新行)

declare
  v_emp emp%rowtype;             --设置一个变量
  cursor c_emp is              --设置一个显示游标,找出奖金为空的数据进行更新
    select * from emp where comm is null for update;
begin
  open c_emp;              --开启游标  
  fetch c_emp             --抓取游标指向的行放入v_emp变量中
    into v_emp;
  while c_emp%found loop        --符合游标条件的值进行循环,即遍历奖金为空的数据行
    update emp set comm = 0 where current of c_emp;      --将奖金为空更新成奖金为0
    fetch c_emp                --循环抓取游标指向的行放入v_emp变量中
      into v_emp;
  end loop;                  --结束循环
  close c_emp;                --关闭游标
end;

--‘where current of c_emp’在此题中即为comm is null,即设置显示游标时对游标设置的条件

--将上级编号为7698的员工工资上涨200(传参,显示游标更新行)

declare
  v_emp emp%rowtype;             --设置一个变量,数据类型与emp表中数据相同
  cursor c_emp(aa number) is        --设置一个显示游标,数据类型为数值,别名aa
    select * from emp where mgr = aa for update;    --找出上级编号为设置的aa参数的数据进行更新
begin
  open c_emp(7698);               --开启游标,7698即为参数aa的值,在此处标明
  fetch c_emp                --抓取游标指向的行放入v_emp变量中
    into v_emp;
  while c_emp%found loop          --符合游标条件的值进行循环,即遍历上级编号为7698的行
    update emp set sal = sal + 200 where current of c_emp;      -将工资更新为上涨200
    fetch c_emp              --循环抓取游标指向的行放入变量v_emp中
      into v_emp;
  end loop;                    --结束循环
  close c_emp;                  --关闭游标
end;