在定义又表示必须要带有for update子句,用于在游标结果集数据上加行共享锁,以防止其他用户在相应行上执行dml操作;当select语句引用到多张表时,使用of子句可以确定哪些表要加锁,如果没有of子句,则会在select语句所引用的全部表上加锁;nowait子句用于指定不等待锁。在提取了游标数据之后,为了更新或删除当前游标行数据,必须在update或delete语句中引用where current of 子句。
--1、使用游标更新数据
--2、使用游标删除数据,同上只需要将更新语句换成删除语句
--3、使用of子句在特定表上加行共享锁
--4、默认情况下当前会话要一直等待对方释放锁,使用nowait子句可以避免等待锁
--1、使用游标更新数据
Java代码
- declare
- cursor emp_cursor is
- --加行共享锁
- select t.name,t.english_name from communitytype t for update;
- --定义变量
- v_name communitytype.name%type;
- v_enname communitytype.english_name%type;
- begin
- --打开游标
- open emp_cursor;
- loop
- fetch emp_cursor into v_name,v_enname;
- exit when emp_cursor%notfound;
- if v_name = '电子图书' then
- update communitytype c
- set c.english_name = 'ebook'
- where current of emp_cursor;
- end if;
- end loop;
- close emp_cursor;
- commit;
- end;
declare cursor emp_cursor is --加行共享锁 select t.name,t.english_name from communitytype t for update; --定义变量 v_name communitytype.name%type; v_enname communitytype.english_name%type; begin --打开游标 open emp_cursor; loop fetch emp_cursor into v_name,v_enname; exit when emp_cursor%notfound; if v_name = '电子图书' then update communitytype c set c.english_name = 'ebook' where current of emp_cursor; end if; end loop; close emp_cursor; commit; end;
--2、使用游标删除数据,同上只需要将更新语句换成删除语句
--3、使用of子句在特定表上加行共享锁
Java代码
- declare
- cursor emp_cursor is
- --加行共享锁
- select t.name,t.english_name from communitytype t for update of t.name;
- --定义基于游标的记录变量
- emp_record emp_cursor%rowtype;
- begin
- --打开游标
- open emp_cursor;
- loop
- fetch emp_cursor into emp_record;
- exit when emp_cursor%notfound;
- if emp_record.name = '电子图书' then
- update communitytype c
- set c.english_name = 'ebook'
- where current of emp_cursor;
- end if;
- end loop;
- close emp_cursor;
- commit;
- end;
declare cursor emp_cursor is --加行共享锁 select t.name,t.english_name from communitytype t for update of t.name; --定义基于游标的记录变量 emp_record emp_cursor%rowtype; begin --打开游标 open emp_cursor; loop fetch emp_cursor into emp_record; exit when emp_cursor%notfound; if emp_record.name = '电子图书' then update communitytype c set c.english_name = 'ebook' where current of emp_cursor; end if; end loop; close emp_cursor; commit; end;
--4、默认情况下当前会话要一直等待对方释放锁,使用nowait子句可以避免等待锁
Java代码
- declare
- cursor emp_cursor is
- --加行共享锁
- select t.name,t.english_name from communitytype t for update nowait;
- --定义基于游标的记录变量
- emp_record emp_cursor%rowtype;
- begin
- --打开游标
- open emp_cursor;
- loop
- fetch emp_cursor into emp_record;
- exit when emp_cursor%notfound;
- if emp_record.name = '电子图书' then
- update communitytype c
- set c.english_name = 'ebook'
- where current of emp_cursor;
- end if;
- end loop;
- close emp_cursor;
- commit;
- end;