plsq游标笔记

游标可以分为显示游标和隐式游标。

  1. 隐式游标:由ORACLE服务器自动创建和管理,用户是不能访问隐式游标。当必须执行SQL语句时,orcale服务器自动创建一个这样的游标。

  2. 显示游标:由用户自己声明。


    隐式游标访问方式:

    1. SQL%not found:最近的sql语句返回至少一行数据时,为True。

    2. SQL%not found:最近一次sql语句没有返回数据时,为true

    3. SQL%rowcount :最近一次sql语句影响的行数


    显式游标:

    • 游标的操作包括:声明,打开,提取,关闭操作。

    注意:第一次提取某个游标时test_cusor%not foundtest_cusor%found值为NULL。因此作为循环结束的条件时,需要注意再加一个条件test_cusor%not found or test_cusor%not found is null

    xxx不用声明,直接表示cursor的一条数据,快速访问游标的方法:
    for xxx in cursor loop
    end loop
    
  • 游标可以带参数。

     --定义
     declare cursor test_cursor(arg1 number,agr2 number) 
          is select * 
              from temp_table 
              where temp_table.id =  arg1 and  temp_table.no =arg2;
      --打开
      open test_cursor(1,2);
      --访问数据方式1
      for temp_record in test_cursor loop
      end loop;
      --访问数据方式2
      fetch  test_cursor into temp_1,temp_2
      exit when 退出条件
      
    
  • select for update,当我们从数据库表里查询了数据后,需要更新然后写回表里,这时候可以使用for update 。写回表里的时候可能他人修改了表,造成冲突,因此需要锁住表(这里是行级锁)。另外select for update 不会使单纯的select阻塞。对 select for update 、insert、update、delete操作默认加行级锁。

    select ...
    from ...
    for update [column_reference] [wait n| nowait]
    --column_reference 表的列
    --nowait 如果被其他会话锁住,无需等待,直接返回错误
    --wait n 如果被其他会话锁住,等待n秒,n秒后还是被锁,直接返回错误
    
    • select for update 是为了获取那些需要修改的数据,而where current of 则是为了修改那些select for update的数据。where current of 需要和 select for update配合使用。where current of接在update和delete后面。例如where current of cursor_name
    for cursor_record in cursor_name loop
    update table_name 
    set xxx=xxx
    where current of cursor_name;
    end loop;
        
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值