關(guān)于Oracle中update |
發(fā)布時(shí)間: 2012/8/21 16:58:03 |
前幾天用到Oracle數(shù)據(jù)庫(kù)的update更新,對(duì)于這個(gè)簡(jiǎn)單問題,卻出現(xiàn)了不少問題,所以現(xiàn)將從網(wǎng)上搜索資料及自已的總結(jié)羅列在此以備一時(shí)之用. 以下所列sql都是基于下表 create table test (name varchar2(30),code varchar2(10),i_d varchar2(10)); 插入數(shù)據(jù) - 1. update 更新i_d為1的數(shù)據(jù) --方式1 這樣可以成功 --方式2 update test set (name,code)=( 注意,這樣是不行,update set 必須為子查詢,所以需要將其改為 : --方式3 update test set (name,code)=( commit; 2.update 說完了,下面寫一下關(guān)于for update,for update of 下面的資料是從網(wǎng)上找到的,可是具體的網(wǎng)址現(xiàn)在找不到了,請(qǐng)?jiān)徯〉艿拇中模萌思业臇|東而不寫出處. for update 經(jīng)常用,而for updade of 卻不常用,現(xiàn)在將這兩個(gè)作一個(gè)區(qū)分 a. select * from test for update 鎖定表的所有行,只能讀不能寫 b. select * from test where i_d = 1 for update 只鎖定i_d=1的行,對(duì)于其他的表的其他行卻不鎖定 下面再創(chuàng)建一個(gè)表 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; 這樣則會(huì)鎖定兩張表的所有數(shù)據(jù) d. select * from test a join t on a.i_d=t.dept_id where a.i_d=1 for update; 這樣則會(huì)鎖定滿足條件的數(shù)據(jù) 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; 注意區(qū)分 d與e,e只分鎖定表test中滿足條件的數(shù)據(jù)行,而不會(huì)鎖定表t中的數(shù)據(jù),因?yàn)橹霸趐rocedure中作一個(gè)update,而需要update的數(shù)據(jù)需要關(guān)聯(lián)查詢,所以用了for update造成其他用戶更新造成阻塞,所以才查到這段資料. for update of 是一個(gè)行級(jí)鎖,這個(gè)行級(jí)鎖,開始于一個(gè)cursor 打開時(shí),而終止于事務(wù)的commit或rollback,而并非cursor的close. 如果有兩個(gè)cursor對(duì)于表的同一行記錄同時(shí)進(jìn)行update,實(shí)際上只有一個(gè)cursor在執(zhí)行,而另外一個(gè)一直在等待,直至另一個(gè)完成,它自己再執(zhí)行.如果第一個(gè)cursor不能被很好的處理,第二個(gè)cursor也不主動(dòng)釋放資源,則死鎖就此產(chǎn)生. 執(zhí)行如下代碼就會(huì)死鎖(在兩個(gè)command window中執(zhí)行) declare for rec in cur_test loop declare for rec in cur_test loop 注意兩個(gè)pl/sql塊中沒有commit; 為了解決這個(gè)死鎖問題,要么就是第一個(gè)塊釋放資源,要么就是第二塊主動(dòng)放棄.第一次釋放資源很簡(jiǎn)單,那就執(zhí)行commit或rollback;而讓第二塊主動(dòng)放棄,在for update 后加no wait;這樣就會(huì)報(bào) ORA-00054 [resource busy and acquire with NOWAIT specified 的錯(cuò)誤,這樣就沒有死鎖了. 本文出自:億恩科技【www.cmtents.com】 服務(wù)器租用/服務(wù)器托管中國(guó)五強(qiáng)!虛擬主機(jī)域名注冊(cè)頂級(jí)提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM] |