序段:
declare test_cur cursor with hold for
select .... from A where ... order by ... with ur;
open test_cur;
while( 1 ){
fecth test_cur into ......;
判斷SQLCODE
begin_work(); /* 其實(shí)就是設(shè)置了一個(gè)標(biāo)志 */
SQL 操作,修改其他表或者游標(biāo)所在表的
數(shù)據(jù)。
根據(jù)結(jié)果判斷 commit or rollback。 /* 此處如果rollback 游標(biāo)被關(guān)閉 */
}
異常狀態(tài):
如果游標(biāo)中進(jìn)行了SQL操作,根據(jù)結(jié)果判斷并rollback時(shí),
下一次fetch時(shí),會(huì)提示 501 沒(méi)有打開(kāi)游標(biāo)。從而報(bào)錯(cuò)退出。
------------------------------
疑問(wèn):
使用前參考的文章:
http://searchdatabase.techtarget.com.cn/tips/365/2297365.shtml之中有說(shuō)到:
10.DB2的游標(biāo)打開(kāi)后遇到commit和rollback默認(rèn)是會(huì)關(guān)閉的。保持游標(biāo)打開(kāi)的方法是在定義游標(biāo)時(shí)加上with hold選項(xiàng)
但是,我declare 游標(biāo)時(shí)使用了with hold選項(xiàng),為什么還會(huì)出現(xiàn)這個(gè)問(wèn)題?
額賣糕的
從vlife以前的回復(fù)中找到的答案: 無(wú)論是否使用with hold與否,rollback將釋放session中的游標(biāo)。commit只釋放不帶with hold的游標(biāo)。 -------------------------------- 救命啊。這些程序是從informix移植過(guò)來(lái)的。 難道讓我將滿足條件的記錄全部讀到一個(gè)結(jié)構(gòu)數(shù)組里面,然后再?gòu)慕Y(jié)構(gòu)數(shù)組里面逐條取出處理么? 量很大的哈。。。。我死了。。。 |
摘自《SQL Reference Volume 2》
declare Cursor WITH HOLD
Maintains resources across multiple units of work.
(1)For units of work ending with COMMIT:
- Open cursors defined WITH HOLD remain open.
- All locks are released, except locks protecting the current cursor position of open WITH HOLD cursors.
。。。
(2)For units of work ending with ROLLBACK:
-All open cursors are closed.
-All locks acquired during the unit of work
這種方案是否可行
游標(biāo)改用普通游標(biāo)。 游標(biāo)取出當(dāng)前記錄后,fork子進(jìn)程。 主進(jìn)程只管從游標(biāo)取數(shù)。 子進(jìn)程進(jìn)行事務(wù)、處理、判斷、修改狀態(tài)、提交等等。 主進(jìn)程等子進(jìn)程的結(jié)束信號(hào),然后取下一條記錄。 程序段: declare test_cur cursor with hold for select .... from A where ... order by ... with ur;
open test_cur; while( 1 ){ fecth test_cur into ......; 判斷SQLCODE
pid = fork();
if( pid == 0 ) { /* 子進(jìn)程干活 */ sqledtin( &sqlca ); setsid(); signal( SIGHUP, SIG_IGN );
db_disconn( G_mdb_name ); begin_work(); /* 其實(shí)就是設(shè)置了一個(gè)標(biāo)志 */ SQL 操作,修改其他表或者游標(biāo)所在表的數(shù)據(jù)。 根據(jù)結(jié)果判斷 commit or rollback。 db_disconn(); exit(); }
/* 主進(jìn)程等待子進(jìn)程結(jié)束 */ } close test_cur; |
如果是兩個(gè)不同的事務(wù)的話,你用CLI來(lái)寫(xiě)比較方便
用savepoint
在cursor內(nèi)部設(shè)立一個(gè)savepoint, rollback時(shí)用 rollback to savepoint a; |