重庆思庄Oracle、KingBase、PostgreSQL、Redhat认证学习论坛

标题: Oracle 10g使用游标更新或删除数据 [打印本页]

作者: 郑全    时间: 2014-3-20 12:29
标题: Oracle 10g使用游标更新或删除数据
在定义又表示必须要带有for update子句,用于在游标结果集数据上加行共享锁,以防止其他用户在相应行上执行dml操作;当select语句引用到多张表时,使用of子句可以确定哪些表要加锁,如果没有of子句,则会在select语句所引用的全部表上加锁;nowait子句用于指定不等待锁。在提取了游标数据之后,为了更新或删除当前游标行数据,必须在update或delete语句中引用where current of 子句。 
--1、使用游标更新数据 
  declare
  --加行共享锁 
  cursor emp_cursor is
    SELECT employee_id, last_name FROM employees for update of salary;
  --定义基于游标的记录变量  
  emp_record emp_cursor%rowtype;
  
begin
  --打开游标  
  open emp_cursor;
  loop
    fetch emp_cursor
      into emp_record;
    exit when emp_cursor%notfound;
    if emp_record.employee_id = 100 then
      dbms_output.put_line(emp_record.last_name);
      update employees c
         set c.last_name = 'abc' 
       where current of emp_cursor;
      dbms_output.put_line(emp_record.last_name);
    end if;
  end loop;
  close emp_cursor;
  
  commit;
 dbms_output.put_line(emp_record.last_name);
end;

作者: 郑全    时间: 2014-3-20 12:31
标题: --4、默认情况下当前会话要一直等待对方释放锁,使用nowait子句可以避免等待锁
--4、默认情况下当前会话要一直等待对方释放锁,使用nowait子句可以避免等待锁 

declare
  --加行共享锁 
  cursor emp_cursor is
    SELECT employee_id, last_name FROM employees for update of salary 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.employee_id = 100 then
      dbms_output.put_line(emp_record.last_name);
      update employees c
         set c.last_name = 'abc' 
       where current of emp_cursor;
      dbms_output.put_line(emp_record.last_name);
    end if;
  end loop;
  close emp_cursor;
  
  commit;
 dbms_output.put_line(emp_record.last_name);
end;






欢迎光临 重庆思庄Oracle、KingBase、PostgreSQL、Redhat认证学习论坛 (http://bbs.cqsztech.com/) Powered by Discuz! X3.2