游标可以分为显示游标和隐式游标。
-
隐式游标:由ORACLE服务器自动创建和管理,用户是不能访问隐式游标。当必须执行SQL语句时,orcale服务器自动创建一个这样的游标。
-
显示游标:由用户自己声明。
隐式游标访问方式:
-
SQL%not found:最近的sql语句返回至少一行数据时,为True。
-
SQL%not found:最近一次sql语句没有返回数据时,为true
-
SQL%rowcount :最近一次sql语句影响的行数
显式游标:
- 游标的操作包括:声明,打开,提取,关闭操作。
注意:第一次提取某个游标时
test_cusor%not found
和test_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;
- select for update 是为了获取那些需要修改的数据,而where current of 则是为了修改那些select for update的数据。where current of 需要和 select for update配合使用。where current of接在update和delete后面。例如