TrueVoid 发表于 2013-2-5 01:30:46

游标(指针)

*游标可以减少程序与数据库的交互和内存的消耗。
1.游标分类
    1.1:显示游标
    1.2:隐式游标——SQL;
2.隐式游标
    2.1:功能——操作单行查询数据和DML
    2.2:使用
    2.3:特点
      2.3.1:系统创建;调用游标时打开,用完后立即关闭。
      2.3.2:提交事物后,属性初始化。
      2.3.3:SQL游标是唯一的
      2.3.4:open属性永远为FALSE,永远都可以访问。
      2.3.
3.显示游标
   3.1:功能——操作多行查询数据
   3.2:使用游标的步骤
        declare
        cursor cur_emp is select *from emp——3.2.1:定义(c)
        row_emp cur_emp%rowtype;
        begin
        open cur_emp;——3.2.2:打开游标(o) 
        fetch cur_emp into row_emp;——3.2.3:提取数据(f)
        while cur_emp%found——3.2.4:循环(w)
        loop
                dems_output.put_line(row_emp.empno);——输出记录的语句
                fetch cur_emp into row_emp;
        end loop;
        close cur_emp;——3.2.5:关闭游标(c)
        end;              
   3.3:特点
4.游标的属性
   4.1:%isopen——游标是否打开
   4.2:%found——从结果集中找到作用行
   4.3:%notfound——没有从结果集中找到作用行
   4.4:%rowcount——到当前行为止已经提取的实际行数
5.1:参数游标——带有形参的游标,用于动态绑定。
    *形参类型不需要制定长度,只需制定数据类型。
    *参数游标要在与之绑定的sql语句的where中使用
5.2:游标变量
 
 
 
 
 
 
 
5.3:游标表达式——在游标的sql语句中包含游标。
       *cursor dept_cursor(no number) is
              selecta.dname,cursor(select ename,sal from emp where deptno=a.deptno)
              from dept a where a.deptno=no;
6.游标for循环——中作中常用来代替显示游标,工作中称为隐式游标。
   6.1格式——for record_name in cursor_name loop 执行语句 end loop;
           *record_name——数据库隐含定义的记录变量名,用户自己给。
           *游标自己隐式打开或循环完毕后自己关闭。
           *循环一次,取一次数据。
7.应用
   7.1:数据更新
    declare
       cursor emp_cursor is select ename,sal from emp for update;
*for update——锁定行;of——锁定特定表,默认全部相关表;nowait——不会为获得锁而等待,直接报错。
       v_ename emp.ename%type;
       v_oldsal emp.sal%type;
begin
     open emp_cursor;
     loop
         fetch emp_cursor into v_ename, v_oldsal;
         exit when emp_cursor%notfound;
         if v_oldsal<2000 then
            update emp set sal=sal+100 where current of emp_cursor;
         end if;
     end loop;
     close emp_cursor;
end;
/
页: [1]
查看完整版本: 游标(指针)