DB2數(shù)據(jù)庫編程序要用到的小技巧有哪些?
以下的文章主要向大家講述的是DB2數(shù)據(jù)庫編程序的一些小操作技巧,我在一個信譽度很好的網(wǎng)站找到一個關(guān)于DB2編程序的一些小操作技巧的資料,拿出來供大家分享,以下的文章就是對相關(guān)內(nèi)容的描述。
 
1. 建存儲過程時Create 后一定不要用TAB鍵
- create procedure
 
的create后只能用空格,而不可用tab健,否則編譯會通不過。 切記,切記。
2. 使用臨時表
要注意,臨時表只能建在user tempory tables space 上,如果database只有system tempory table space是不能建臨時表的。
另外,DB2的臨時表和sybase及oracle的臨時表不太一樣,DB2數(shù)據(jù)庫的臨時表是在一個session內(nèi)有效的。所以,如果程序有多線程,最好不要用臨時表,很難控制。
建臨時表時最好加上 with replace選項,這樣就可以不顯示的drop 臨時表,建臨時表時如果不加該選項而該臨時表在該session內(nèi)已創(chuàng)建且沒有drop,這時會發(fā)生錯誤。
3. 從數(shù)據(jù)表中取指定前幾條記錄
- select * from tb_market_code fetch first 1 rows only
 
但下面這種方式不允許
- select market_code into v_market_code
 - from tb_market_code fetch first 1 rows only;
 
選第一條記錄的字段到一個變量以以下方式代替
- declare v_market_code char(1);
 - declare cursor1 cursor for select market_code from tb_market_code
 - fetch first 1 rows only for update;
 - open cursor1;
 - fetch cursor1 into v_market_code;
 - close cursor1;
 
4. 游標(biāo)的使用
注意commit和rollback
使用游標(biāo)時要特別注意如果沒有加with hold 選項,在Commit和Rollback時,該游標(biāo)將被關(guān)閉。Commit 和Rollback有很多東西要注意。特別小心
游標(biāo)的兩種定義方式
一種為
- declare continue handler for not found
 - begin
 - set v_notfound = 1;
 - end;
 - declare cursor1 cursor with hold for select market_code from tb_market_code for update;
 - open cursor1;
 - set v_notfound=0;
 - fetch cursor1 into v_market_code;
 - while v_notfound=0 Do
 - --work
 - set v_notfound=0;
 - fetch cursor1 into v_market_code;
 - end while;
 - close cursor1;
 
這種方式使用起來比較復(fù)雜,但也比較靈活。特別是可以使用with hold 選項。如果循環(huán)內(nèi)有commit或rollback 而要保持該cursor不被關(guān)閉,只能使用這種方式。
另一種為
- pcursor1: for loopcs1 as cousor1 cursor as
 - select market_code as market_code
 - from tb_market_code
 - for update
 - do
 - end for;
 
這種方式的優(yōu)點是比較簡單,不用(也不允許)使用open,fetch,close。
但不能使用with hold 選項。如果在游標(biāo)循環(huán)內(nèi)要使用commit,rollback則不能使用這種方式。如果沒有commit或rollback的要求,推薦使用這種方式(看來For這種方式有問題)。
修改游標(biāo)的當(dāng)前記錄的方法
- update tb_market_code set market_code='0' where current of cursor1;
 
不過要注意將cursor1定義為可修改的游標(biāo)
- declare cursor1 cursor for select market_code from tb_market_code
 - for update;
 
for update 不能和GROUP BY、 DISTINCT、 ORDER BY、 FOR READ ONLY及UNION, EXCEPT, or INTERSECT但 UNION ALL除外)一起使用。
5. 類似decode的轉(zhuǎn)碼操作
oracle中有一個函數(shù) select decode(a1,'1','n1','2','n2','n3') aa1 from
DB2數(shù)據(jù)庫沒有該函數(shù),但可以用變通的方法
- select case a1
 - when '1' then 'n1'
 - when '2' then 'n2'
 - else 'n3'
 - end as aa1 from
 
6. 類似charindex查找字符在字串中的位置
Locate(‘y’,’dfdasfay’)
查找’y’ 在’dfdasfay’中的位置。
7. 類似datedif計算兩個日期的相差天數(shù)
- days(date(‘2001-06-05’)) – days(date(‘2001-04-01’))
 
days 返回的是從 0001-01-01 開始計算的天數(shù)
8. 寫UDF的例子
C寫見sqllib\samples\cli\udfsrv.c
9.創(chuàng)建含identity值(即自動生成的ID)的表
建這樣的表的寫法
- CREATE TABLE test
 - (t1 SMALLINT NOT NULL
 - GENERATED ALWAYS AS IDENTITY
 - (START WITH 500, INCREMENT BY 1),
 - t2 CHAR(1));
 
在一個表中只允許有一個identity的column.以上的相關(guān)內(nèi)容就是對DB2數(shù)據(jù)庫編程序的一些小操作技巧的介紹,望你能有所收獲。
 
【編輯推薦】















 
 
 
 
 
 
 