關於Oracle中update

來源:互聯網
上載者:User

前幾天用到Oracle資料庫的update更新,對於這個簡單問題,卻出現了不少問題,所以現將從網上搜尋資料及自已的總結羅列在此以備一時之用.

以下所列sql都是基於下表

create table test (name  varchar2(30),code varchar2(10),i_d varchar2(10));

插入資料

insert into test(name,code,i_d) values('zhu1','001','1');
insert into test(name,code,i_d) values('zhu2','002','2');
insert into test(name,code,i_d) values('zhu3','003','3');
commit;
select * from test s;

1. update 更新i_d為1的資料

--方式1
update test  set name='zhurhyme1',
code='007' where i_d='1';
commit;

這樣可以成功

--方式2

update test set (name,code)=(
'zhurhyme2','007')
where i_d='1';

注意,這樣是不行,update set 必須為子查詢,所以需要將其改為 :

--方式3

update test set (name,code)=(
select 'zhurhyme3','007' from dual)
where i_d='1';

commit;

2.update 說完了,下面寫一下關於for update,for update of

 下面的資料是從網上找到的,可是具體的網址現在找不到了,請原諒小弟的粗心,引用人家的東東而不寫出處.

for update 經常用,而for updade of 卻不常用,現在將這兩個作一個區分

a.    select * from test for update 鎖定表的所有行,只能讀不能寫

b.  select * from test where i_d = 1 for update 只鎖定i_d=1的行,對於其他的表的其他行卻不鎖定

下面再建立一個表

create table t (dept_id  varchar(10),dept_name varchar2(50));

c.  select * from test  a join t on a.i_d=t.dept_id for update;  這樣則會鎖定兩張表的所有資料

d.  select * from test  a join t on a.i_d=t.dept_id where a.i_d=1 for update;  這樣則會鎖定滿足條件的資料

e.  select * from test  a join t on a.i_d=t.dept_id where a.i_d=1 for update of a.i_d; 注意區分 d與e,e只分鎖定表test中滿足條件的資料行,而不會鎖定表t中的資料,因為之前在procedure中作一個update,而需要update的資料需要關聯查詢,所以用了for update造成其他使用者更新造成阻塞,所以才查到這段資料.

 for update of 是一個行級鎖,這個行級鎖,開始於一個cursor 開啟時,而終止於事務的commit或rollback,而並非cursor的close.

如果有兩個cursor對於表的同一行記錄同時進行update,實際上只有一個cursor在執行,而另外一個一直在等待,直至另一個完成,它自己再執行.如果第一個cursor不能被很好的處理,第二個cursor也不主動釋放資源,則死結就此產生.

執行如下代碼就會死結(在兩個command window中執行)

declare
 cursor cur_test
   is
   select name,code from test where i_d=1 for update of name;
begin

   for rec in cur_test loop
      update test set name='TTTT1' where current of cur_test;
 end loop;
end;
/

declare
 cursor cur_test
   is
   select name,code from test where i_d=1 for update of name;
begin

   for rec in cur_test loop
      update test set name='TTTT2' where current of cur_test;
 end loop;
end;
/

注意兩個pl/sql塊中沒有commit;

為瞭解決這個死結問題,要麼就是第一個塊釋放資源,要麼就是第二塊主動放棄.第一次釋放資源很簡單,那就執行commit或rollback;而讓第二塊主動放棄,在for update 後加no wait;這樣就會報

ORA-00054 [resource busy and acquire with NOWAIT specified 的錯誤,這樣就沒有死結了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.