1DB2编程1.1创建存储过程时不要在Create后使用TAB键。createprocedure的create之后,只能使用空格,不能使用tab键,否则编译不通过。记住,记住。1.2注意临时表的使用。临时表只能建立在usertemporytablesspace上。如果数据库只有systemtemporytablespace,则无法建临时表。另外,DB2的临时表与Sybase、Oracle的临时表不同。DB2的临时表在一个会话内有效。因此,如果程序有多个线程,最好不要使用临时表,很难控制。最好在创建临时表的时候加上withreplace选项,这样drop临时表就不能显示了。如果在创建临时表的时候没有加这个选项,而临时表已经在session中创建了,没有drop,这时候就会报错。1.3从数据表中取指定前几条记录select*fromtb_market_codefetchfirst1rowsonly但下面这种方式不允许selectmarket_codeintov_market_codefromtb_market_codefetchfirst1rowsonly;选第一条记录的字段到一个变量以以下方式代替declarev_market_codechar(1);declarecursor1cursorforselectmarket_codefromtb_market_codefetchfirst1rowsonlyforupdate;opencursor1;fetchcursor1intov_market_code;closecursor1;1.4Cursor的使用使用游标时要注意commit和rollback。如果不加withhold选项,在Commit和Rollback的时候游标会被关闭。Commit和Rollback有很多需要注意的地方。特别小心游标的两种定义方式一种为declarecontinuehandlerfornotfoundbeginsetv_notfound=1;end;declarecursor1cursorwithholdforselectmarket_codefromtb_market_codeforupdate;opencursor1;setv_notfound=0;fetchcursor1intov_market_code;whilev_notfound=0Do--worksetv_notfound=0;fetchcursor1intov_market_code;endwhile;closecursor1;这种方式使用起来比较复杂,而且也比较灵活。特别是可以使用保留选项。只有在循环中有提交或回滚并且不应关闭游标时才能使用此方法。另一个是pcursor1:forloopcs1ascousor1cursorasseselectmarket_codeasmarket_codefromtb_market_codeforupdatedoendfor;这种方法的优点是比较简单,不需要(也不允许)使用open、fetch和close。但是不能使用保留选项。如果要在游标循环中使用提交和回滚,则不能使用此方法。如果没有commit或者rollback的要求,推荐这种方式(For的这种方式好像有问题)。修改游标当前记录的方法updatetb_market_codesetmarket_code='0'wherecurrentofcursor1;但请注意,cursor1被定义为可修改游标declarecursor1cursorforselectmarket_codefromtb_market_codeforupdate;forupdate不能与GROUPBY、DISTINCT、ORDERBY、FORREADONLY和UNION、EXCEPT或NA一起使用)。1.5类似于decode的转码操作有一个函数selectdecode(a1,'1','n1','2','n2','n3')aa1fromdb2在oracle中没有这个函数,但是可以使用一个workaroundselectcasea1when'1'then'n1'when'2'then'n2'else'n3'endasaa1from1.6类似于charindex查找字符在字符串中的位置locate('y','dfdasfay')查找'y'在'dfdasfay'位置。1.7类似datedif计算两个日期days(date('2001-06-05'))–days之间的天数差
