oracle 游标

时间:2019-08-20
本文章向大家介绍oracle 游标,主要包括oracle 游标使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

oracle 游标

select * from myuser for update;
begin
    update myuser set password='654321' where id=5;
    dbms_output.put_line('上述操作影响了'||sql%rowcount||'条记录');
    if(sql%found) then 
        dbms_output.put_line('有找到要修改的数据');
    else
        dbms_output.put_line('未找到数据');  
    end if;
end;

--最简单的游标,定义指向scott.emp 表记录集的游标,并且遍历
--使用游标遍历输出所有职员的编号和姓名
declare
    cursor mycur       --1、定义游标
    is 
    select empno,ename from scott.emp;
    v_empno scott.emp.empno%type;
    v_ename scott.emp.ename%type;
begin
    --2、打开游标
    if(not mycur%isopen) then
         open mycur;
    end if;
    --3、从游标中提取记录
    loop
     fetch mycur into v_empno,v_ename;
           if(mycur%notfound) then
                 exit;
           end if;
           dbms_output.put_line('第'||mycur%rowcount||'记录:'||v_empno||','||v_ename);
    end loop;
    --4、关闭游标
    close mycur;
end;


--带参数的游标
--使用游标遍历输出指定部门的所有职员的姓名和编号
declare
    cursor mycur(v_deptno number)       --1、定义游标
    is 
    select empno,ename from scott.emp where deptno=v_deptno;
    v_empno scott.emp.empno%type;
    v_ename scott.emp.ename%type;
begin
    --2、打开游标
    if(not mycur%isopen) then
         open mycur('&deptno');
    end if;
    --3、从游标中提取记录
    loop
     fetch mycur into v_empno,v_ename;
           if(mycur%notfound) then
                 exit;
           end if;
           dbms_output.put_line('第'||mycur%rowcount||'记录:'||v_empno||','||v_ename);
    end loop;
    --4、关闭游标
    close mycur;
end;

--强制写入的游标
--对指定部门的员工薪资提升10%
declare
    cursor mycur(v_deptno number)       --1、定义游标
    is 
    select empno from scott.emp_temp where deptno=v_deptno for update of sal nowait;
     --无需进行事务等待的强制读取,避免死锁,多线程条件下相对安全的写入机制,如果没有 of sal的话就支持全表更新。
    v_empno scott.emp_temp.empno%type;
begin
    --2、打开游标
    if(not mycur%isopen) then
         open mycur('&deptno');
    end if;
    --3、从游标中提取记录
    loop
     fetch mycur into v_empno;
           if(mycur%notfound) then
                 exit;
           end if;
           update scott.emp_temp set sal=sal*1.1 where empno=v_empno;
    end loop;
    commit;
        dbms_output.put_line('上述操作更新了'||sql%rowcount||'条记录');
    --4、关闭游标
    close mycur;
end;

--游标简化1:
declare
    cursor mycur(v_deptno number)--1、定义游标
    is
    select empno,ename from scott.emp where deptno=v_deptno;
begin
--2、使用游标提取
    for cur in mycur('&deptno') loop
               dbms_output.put_line('第'||mycur%rowcount||'记录:'||cur.empno||','||cur.empno);
    end loop;
end;


----游标简化2:
begin
    for cur in (select empno,ename from scott.emp where deptno='&deptno') loop
               dbms_output.put_line(cur.empno||','||cur.empno);
    end loop;
end;

--什么时候用简化1?简化2?
--批量修改数据的时候用简化2。写存储过程或者函数的时候用简化1


create table emp_temp as select * from emp;
select * from emp_temp;

原文地址:https://www.cnblogs.com/Jotal/p/11381911.html