1. 程式人生 > >Oracle使用遊標更新資料 Oracle遊標之select for update和where current of 語句

Oracle使用遊標更新資料 Oracle遊標之select for update和where current of 語句

Oracle使用遊標更新資料

2016年11月20日 13:15:49 hzwy23 閱讀數:5313


友情推廣
在這裡插入圖片描述

###使用遊標修改資料

####定義一個遊標,遊標名稱為 mycursor

#####更新scott使用者中emp表中empno為7369的銷售額

-- Created on 2015/11/30 by ZHANW 
declare 
  he emp%rowtype;
  cursor mycursor(pid integer) is select * from emp where empno = pid for update;
begin
  open mycursor(7369);
  while(true) loop
     fetch mycursor into he; 
     exit when mycursor%notfound;
     update emp set sal = 1111 where current of mycursor;
  end loop;
end;
-- Created on 2015/11/30 by ZHANW 
declare 
  he emp%rowtype;
  cursor mycursor(pid integer) is select * from emp where empno = pid for update;
begin
  open mycursor(7369);
  while(true) loop
     fetch mycursor into he; 
     exit when mycursor%notfound;
     delete from emp where current of mycursor;
  end loop;
end;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

###注意:

delete語句一定要寫在exit後面,不然可能會報錯。

####優化:

在定義遊標時,可以在for update 後面新增 of 欄位或者nowait。

https://blog.csdn.net/hzwy23/article/details/53240333

 

 

 

 

Oracle遊標之select for update和where current of 語句

2013年06月27日 10:57:09 luckystar2008 閱讀數:3150

轉載http://hanjiangduqiao.blog.163.com/blog/static/613105442011431111153601

 

使用select for update 語句可以使用行鎖鎖定你要更改的記錄.當遇到下一個commit和rollback語句時會被釋放.

The Select For Update statement allows you to lock the records in the cursor result set. You are not required to make changes to the records in order to use this statement. The record locks are released when the next commit or rollback statement is issued.

語法如下:The syntax for the Select For Update is:

CURSOR cursor_name
IS
   select_statement
   FOR UPDATE [of column_list] [NOWAIT];

當你要使用遊標進行更新和刪除操作時,則需要使用where current of 語句,這個是標示出當前遊標的位置.

If you plan on updating or deleting records that have been referenced by a select for update statement, you can use the Where Current Of statement.

 語法如下:The syntax for the Where Current Of statement is either:

UPDATE table_name
    SET set_clause
    WHERE CURRENT OF cursor_name;

OR

DELETE FROM table_name
WHERE CURRENT OF cursor_name;


在這時的例子中我採用上面所建的test表來試驗.

2.1 更新.

SQL> DECLARE
  2  CURSOR  test_cur IS SELECT  * FROM test
  3  FOR UPDATE OF sal;
  4  BEGIN
  5  FOR test_rec IN  test_cur LOOP
  6  UPDATE test
  7  SET sal = test_rec.sal +1
  8  WHERE CURRENT OF test_cur;
  9  END LOOP;
 10  COMMIT;
 11  END;
 12  /

PL/SQL 過程已成功完成。

2.2 刪除.

SQL> DECLARE
  2  CURSOR test_cur IS select * from test for update;
  3  BEGIN
  4  FOR test_rec IN test_cur LOOP
  5  DELETE FROM test WHERE CURRENT OF test_cur;
  6  END LOOP;
  7  END;
  8  /

PL/SQL 過程已成功完成。

文中的遊標只是簡單的使用,在記錄到pl/sql詳細程式設計的時候會再講到時會結合oracle的執行計劃並一起討論它們的執行效率.

注:文中的英文註解部分出自:http://www.techonthenet.com/oracle/cursors/current_of.php

https://blog.csdn.net/qincidong/article/details/9185693