日期:2014-05-16  浏览次数:20522 次

db2 游标及其他
定义游标:
DECLARE 游标名 CURSOR FOR
   Select 语句;
打开游标:
    OPEN 游标名;
取值:
     FETCH 游标名 INTO 变量列表
例:
DECLARE c1 CURSOR FOR
SELECT CAST(salary AS DOUBLE)
FROM staff
WHERE DEPT = deptNumber
ORDER BY salary;
DECLARE EXIT HANDLER FOR NOT FOUND
SET medianSalary = 6666;
SET medianSalary = 0;
SELECT COUNT(*) INTO v_numRecords
FROM staff
WHERE DEPT = deptNumber;
OPEN c1;
WHILE v_counter < (v_numRecords / 2 + 1) DO
FETCH c1 INTO medianSalary;
SET v_counter = v_counter + 1;
END WHILE;
CLOSE c1;
注:游标的申明如果放在中间段,要用”begin。。。end;”.段分割标志分割开;
动态sql
1) declare stmt varchar(1024);
set stmt='create table zhouhaiming( f1 smallint, f2 varchar(9), f3 char(5) )';
prepare s1 from stmt;
execute s1;
set stmt='insert into zhouhaiming values (1,'www','aaa')';
prepare s1 from stmt;
execute s1;
2) DECLARE CURSOR C1 FOR STMT1;
      PREPARE STMT1 FROM
         'ALLOCATE C2 CURSOR FOR RESULT SET ?';
临时表的建立
DECLARE GLOBAL TEMPORARY TABLE TABLE_NAME
AS (FULLSELECT) DEFINITION ONLY
EXCLUDING IDENTITY COLUMN ATTRIBUTES
   ON COMMIT DELETE ROWS
   NOT LOGGED IN 临时表空间名with   replace;
第一行規定臨時表的名稱.
   第二行規定臨時表的列的定義.
   第三行規定不是從源結果表定義中復制的恒等列.
   第四行規定如果沒有打開WITH GOLD光標,將會刪除表的所有行.
   第五行規定不對表的改變進行記錄.
   With replace选项会隐式的自动删除该临时表。
  例如:
   DECLARE GLOBAL TEMPORARY TABLE DEC_BSEMPMS
   AS (SELECT * FROM BSEMPMS) DEFINITION ONLY
   EXCLUDING IDENTITY COLUMN ATTRIBUTES
   ON COMMIT DELETE ROWS
   NOT LOGGED;
DB2中的几个全局变量
n        ROW_COUNT—影响行数
UPDATE CORPDATA.PROJECT
SET PRSTAFF = PRSTAFF + 1.5
WHERE DEPTNO = deptnbr;
GET DIAGNOSTICSrcount = ROW_COUNT;
n        RETURN_STATUS--返回状态
CALL TRYIT;--调用存储过程
GET DIAGNOSTICSRETVAL = RETURN_STATUS;
IF RETVAL <> 0 THEN
...
LEAVE A1;
ELSE
...
END IF;
n        SQLSTATE—SQL返回错误代码
注:使用前必先定义
declare sqlstate char(5);
declare state char(5);
insert into tbname values(…)
set state=sqlstate;
if(state<> '00000') then
return -1;
end if;     
关于ATOMIC和NOT ATOMIC
P1:BEGIN ATOMIC –P1段的事务会自动回滚
P1:BEGIN NOT ATOMIC –P1段的事务不会自动回滚
DB2中的条件句柄
句柄类型:
n        CONTINUE
n        EXIT
n        UNDO
条件类型:
n        SQLSTATE string
n        SQLEXCEPTION
n        SQLWARNING
n        NOT FOUND
例:
1)DECLARE EXIT HANDLER FOR NOT FOUND
SET medianSalary = 6666;
2) DECLARE not_found CONDITION FOR SQLSTATE '02000';
DECLARE EXIT HANDLER FOR not_found
SET rating = -1;
3)    DECLARE not_found CONDITION FOR SQLSTATE '02000';
DECLARE c1 CURSOR FOR
SELECT deptno, deptname, admrdept
FROM department
ORDER BY deptno;
DECLARE CONTINUE HANDLER FOR not_found
SET at_end = 1;
如何抽取/提交存储过程
db2 "get routine into 文件名 from procedure 存储过程名"
抽取存储过程;
提交存储过程
db2 "put routine from 文件名"
安装已编译好的存储过程。
如何在命令符下提交存储过程
在存储过程的最后加上@符号,然后在命令符下打入:db2 -td@ -vf procfile.sql 就可以生成过程。
非存储过程的SQL文件,在命令符下打入:db2 –tvf sqlfile.sql
从存储过程返回结果集(游标)的用法
1、建一sp返回结果集
CREATE PROCEDURE DB2INST1.Proc1 (