一. 使用存储过程的好处

  1. 减少客户机与服务器之间的网络使用率,以及数据库锁定保持的时间

      应用程序通常在执行每个SQL语句都要跨网络两次,存储过程可以将SQL语句集中在一起,

    从而使得对于每一组SQL语句只需要跨网络两次。存储过程中集中在一起的SQL语句越多,

    网络的使用率和数据库锁定保持的时间就越低。通过减少网络使用率和数据库锁定的时间长短,

    就可以提高网络的总体性能并减少锁定争用问题。

 

二. 用于存储过程的语言

  在DB2的"开发中心",可以用Java或SQL来创建存储过程。

 

三. SQL存储过程

  1. 使用SQL过程语言来编写存储过程具有下列优点:

    a. 可以通过在"开发中心"中使用集成调试器来调试SQL存储过程

    b. 借助SQL存储过程,可以调用其它SQL过程,最多可以嵌套16层调用

    c. SQL存储过程运行速度快,因为它是作为已编译的例程来运行的

  2. SQL存储过程具有大小和参数限制,这取决于正在运行的DB2版本:

    a. 对于DB2 Windows版和UNIX版,在版本7和版本8中,SQL存储过程的最大大小是64KB

 

四. Java存储过程

   1. 使用Java语言来编写存储过程具有下列优点:

    a. 在Java的安全性限制之内,可以使用Java存储过程进行文件的输入/输出。SQL存储过程不支持

      文件的输入/输出。

 

五. 存储过程的基本语法 

create procedure db2Inst.proce1(
    in "inParam" integer,
    out "outParam" varchar(10)
)
specific "proce1"
language sql
dynamic result sets 1
not deterministic
external action
modifies sql data
old savepoint level

begin
    L1: begin
        /*变量定义*/
        declare inum integer default 0;

        /*变量赋值*/
        set inum = 20;

        /*分支语句*/
        if 条件1 then
            ...
        elseif 条件2 then
            ...
        else 
            ...
        end if;

        /*多分支语句case*/
        case 变量名
            when 变量值1 then 
                ...
            when 变量值2 then 
                ...
            else 
                ...
        end case;

        /*for循环*/
        for 变量名 as 游标名或select 表达式
        do
            ...
        end for;

        /*while循环*/
        while 条件表达式 do
            ...
        end while;

        /*loop语句*/
        insLoop:
        loop
            ...
            leave insLoop;/*中断循环*/
            iterate insLoop;/*下一个循环*/
        end loop;

        /*游标的使用方式一*/
        /*定义游标*/
        declare 游标名 cursor for select 语句;
        /*打开游标*/
        open 游标名;
        /*取值*/
        fetch 游标名 into 变量列表;
        /*关闭游标*/
        close 游标名;

        /*goto语句*/
        goto fail;
            ...
        success: return 0
        fail: return -200
        
    end L1;

    /*游标的使用方式二*/
    /*游标的定义如果放在中间段,要用"begin...end;"段分割标志分割开*/
    L2: begin
        declare v_notfound integer default 0;
        declare stmt statement;/*声明放游标的值 */        
        declare cur cursor with return for stmt;/*声明动态游标存储变量*/
        declare continue handler for not found set v_notfound = 1;

        prepare stmt from qrySql;
        open cur;
        fetch cur into 变量列表;
        close cur;
    end L2;
    
    /*临时表*/
    L3: begin
        /*定义临时表*/
        declare global temporary table session.tableName(
                columnName integer
        )
        not logged with replace;/*不记录日志,没有则替换*/
        /*操作临时表*/
        insert into session.tableName values(columnValue);
    end L3;

    /*取得行号*/
    select rownumber() over() as rownum from tableName;

    /*解决like后跟一个字段*/
    select * from table1 a
    left join table2 b on locate(a.columnName,b.columnName)>0;

end
View Code

相关文章: