關(guān)于Oracle中update |
發(fā)布時間: 2012/8/21 16:58:03 |
前幾天用到Oracle數(shù)據(jù)庫的update更新,對于這個簡單問題,卻出現(xiàn)了不少問題,所以現(xiàn)將從網(wǎng)上搜索資料及自已的總結(jié)羅列在此以備一時之用. 以下所列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)在找不到了,請原諒小弟的粗心,引用人家的東東而不寫出處. for update 經(jīng)常用,而for updade of 卻不常用,現(xiàn)在將這兩個作一個區(qū)分 a. select * from test for update 鎖定表的所有行,只能讀不能寫 b. select * from test where i_d = 1 for update 只鎖定i_d=1的行,對于其他的表的其他行卻不鎖定 下面再創(chuàng)建一個表 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; 這樣則會鎖定兩張表的所有數(shù)據(jù) d. select * from test a join t on a.i_d=t.dept_id where a.i_d=1 for update; 這樣則會鎖定滿足條件的數(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ù)行,而不會鎖定表t中的數(shù)據(jù),因為之前在procedure中作一個update,而需要update的數(shù)據(jù)需要關(guān)聯(lián)查詢,所以用了for update造成其他用戶更新造成阻塞,所以才查到這段資料. for update of 是一個行級鎖,這個行級鎖,開始于一個cursor 打開時,而終止于事務的commit或rollback,而并非cursor的close. 如果有兩個cursor對于表的同一行記錄同時進行update,實際上只有一個cursor在執(zhí)行,而另外一個一直在等待,直至另一個完成,它自己再執(zhí)行.如果第一個cursor不能被很好的處理,第二個cursor也不主動釋放資源,則死鎖就此產(chǎn)生. 執(zhí)行如下代碼就會死鎖(在兩個command window中執(zhí)行) declare for rec in cur_test loop declare for rec in cur_test loop 注意兩個pl/sql塊中沒有commit; 為了解決這個死鎖問題,要么就是第一個塊釋放資源,要么就是第二塊主動放棄.第一次釋放資源很簡單,那就執(zhí)行commit或rollback;而讓第二塊主動放棄,在for update 后加no wait;這樣就會報 ORA-00054 [resource busy and acquire with NOWAIT specified 的錯誤,這樣就沒有死鎖了. 本文出自:億恩科技【www.riomediacenter.com】 |