`

DB2SQL存储过程语法官方权威指南(翻译)(转载)

    博客分类:
  • db2
阅读更多

这个还不错,网上这个文章太多了

背景:DB2的数据库性能很牛X,但是其文档却很差,尤其是开发参考文档,都是英文的,浏览的时候还很不好找,需要上IBM的网站看,网站也出奇的慢,极不方便,让开发人员举步维艰,这也许是IBM DB2的用户少,书少,资料少的原因。本人为了搞明白DB2存SQL的完整语法介绍,找遍了WWW,没有发现一篇完整介绍DB2语法的文章,现我根据自己的理解,将IBM对DB2 SQL存储过程的英文翻译下来,与各位网友进行交流,由于时间的限制,没有一字一句的去翻译,只对最核心的语法说明做了简单的翻译工作。我的E文也很差,错误在所难免,欢迎各位给予斧正!
 
译著
------------------
创建SQL存储过程(CREATE PROCEDURE (SQL) statement )
 
语法格式如下:
 
>>-CREATE PROCEDURE--procedure-name----------------------------->
>--+----------------------------------------------------+--*---->
   '-(--+------------------------------------------+--)-'
        | .-,------------------------------------. |
        | V .-IN----.                            | |
        '---+-------+--parameter-name--data-type-+-'
            +-OUT---+
            '-INOUT-'
>--+-------------------------+--*------------------------------->
   '-SPECIFIC--specific-name-'
   .-DYNAMIC RESULT SETS 0--------.     .-MODIFIES SQL DATA-.
>--+------------------------------+--*--+-------------------+--->
   '-DYNAMIC RESULT SETS--integer-'     +-CONTAINS SQL------+
                                        '-READS SQL DATA----'
      .-NOT DETERMINISTIC-.     .-CALLED ON NULL INPUT-.
>--*--+-------------------+--*--+----------------------+--*----->
      '-DETERMINISTIC-----'
   .-INHERIT SPECIAL REGISTERS-.     .-7 OLD SAVEPOINT LEVEL-.
>--+---------------------------+--*--+---------------------+---->
                                     '-7 NEW SAVEPOINT LEVEL-'
      .-LANGUAGE SQL-.     .-7 EXTERNAL ACTION----.
>--7 *--+--------------+--*--+--------------------+--*------------>
                           '-7 NO EXTERNAL ACTION-'
>--+------------------------------+--3 *-------------------------->
   '-3 PARAMETER CCSID--+-3 ASCII---+-'
                      '-3 UNICODE-'
>--| SQL-procedure-body |--------------------------------------><
SQL-procedure-body:
|--SQL-procedure-statement--------------------------------------|
 
语法说明
1、procedure-name: 存储过程的名字,在同一个数据库的同一模式下,不能存在存储过程名相同参数数目相同的存储过程,即使参数的类型不同也不行。
 
2、(IN | OUT | INOUT parameter-name data-type,...) :传入参数
    IN:输入参数
 OUT:输出参数
 INOUT:作为输入输出参数
    parameter-name:参数名字,在此存储过程中唯一的标识符。
 data-type:参数类型,可以接收SQL类型和创建的表。不支持LONG VARCHAR, LONG VARGRAPHIC, DATALINK, REFERENCE和用户自定义类型。

 

3、SPECIFIC specific-name:唯一的特定名称(别名),可以用存储过程名代替,这个特定名称用于dorp存储过程,或者给存储过程添加注视用,但不能调用存储过程。如果不指定,则数据库会自动生成一个yymmddhhmmsshhn时间戳的名字。推荐给出别名。
4、DYNAMIC RESULT SETS integer:指定存储过程返回结果的最大数量。存储过程中虽然没有return语句,但是却能返回结果集。

 

5、CONTAINS SQL, READS SQL DATA, MODIFIES SQL DATA: 指定存储过程中的SQL访问级别
    CONTAINS SQL: 表示存储过程可以执行中,既不可读取 SQL 数据,也不可修改 SQL 数据。
    READS SQL DATA: 表示存储过程可以执行中,可读取SQL,但不可修改 SQL 数据。
    MODIFIES SQL DATA: 表示存储过程可以执行任何 SQL 语句。可以对数据库中的数据进行增加、删除和修改。
 
6、DETERMINISTIC or NOT DETERMINISTIC:表示存储过程是动态或者非动态的。动态的返回的值是不确定的。非动态的存储过程每次执行返回的值是相同的。

 

7、CALLED ON NULL INPUT:表示可以调用存储过程而不管任何的输入参数是否为NULL,并且,任何的OUT或者INOUT参数可以返回一个NULL或者非空值。检验参数是否为NULL是在过程中进行的。

 

8、INHERIT SPECIAL REGISTERS:表示继承专用寄存器。

 

9、OLD SAVEPOINT LEVEL or NEW SAVEPOINT LEVEL:建立存储点。OLD SAVEPOINT LEVEL是默认的存储点。

 

10、LANGUAGE SQL:指定程序的主体用的是SQL语言。

 

11、EXTERNAL ACTION or NO EXTERNAL ACTION:表示存储过程是否执行一些改变理数据库状态的活动,而不通过数据库管理器管。默认是 EXTERNAL ACTION。如果指定为NO EXTERNAL ACTION ,则数据库会确定最最佳优化方案。

 

12、PARAMETER CCSID:指定所有输出字符串数据的编码,默认为UNICODE编码数据库为PARAMETER CCSID UNICODE ,其他的数据库默认为PARAMETER CCSID 3 ASCII。

 

13、SQL-procedure-body:存储过程的主体

例子1:产生一个SQL存储过程,返回员工的平均薪水. 返回所有员工超过平均薪水的数额,结果集包括name, position, and salary字段(参考数据库为db2的示例数据库sample)。
   CREATE PROCEDURE MEDIAN_RESULT_SET (OUT medianSalary DOUBLE)
     RESULT SETS 1
     LANGUAGE SQL
   BEGIN
     DECLARE v_numRecords INT DEFAULT 1;
     DECLARE v_counter INT DEFAULT 0;
     DECLARE c1 CURSOR FOR
       SELECT CAST(salary AS DOUBLE)
         FROM staff
         ORDER BY salary;
     DECLARE c2 CURSOR WITH RETURN FOR
       SELECT name, job, CAST(salary AS INTEGER)
         FROM staff
         WHERE salary > medianSalary
         ORDER BY salary;
     DECLARE EXIT HANDLER FOR NOT FOUND
       SET medianSalary = 6666;
     SET medianSalary = 0;
     SELECT COUNT(*) INTO v_numRecords
       FROM STAFF;
     OPEN c1;
     WHILE v_counter < (v_numRecords / 2 + 1)
     DO
       FETCH c1 INTO medianSalary;
       SET v_counter = v_counter + 1;
     END WHILE;
     CLOSE c1;
     OPEN c2;
   END
 
--------------------
原文如下:
 
CREATE PROCEDURE (SQL) statement
The CREATE PROCEDURE (SQL) statement defines an SQL procedure at the current server.
Invocation
This statement can be embedded in an application program or issued through the use of dynamic SQL statements. It is an executable statement that can be dynamically prepared only if DYNAMICRULES run behavior is in effect for the package (SQLSTATE 42509).
Authorization
The privileges held by the authorization ID of the statement must include at least one of the following:
2 BINDADD privilege on the database, and one of the 2 following: 2 2 2 IMPLICIT_SCHEMA privilege on the database, if the implicit 2 or explicit schema name of the procedure does not exist 2 CREATEIN privilege on the schema, if the schema name of the 2 procedure refers to an existing schema
SYSADM or DBADM authority
If the authorization ID of the statement does not have SYSADM or DBADM authority, the privileges held by the authorization ID of the statement must also include all of the privileges necessary to invoke the SQL statements that are specified in the procedure body.
Syntax
>>-CREATE PROCEDURE--procedure-name----------------------------->
>--+----------------------------------------------------+--*---->
   '-(--+------------------------------------------+--)-'
        | .-,------------------------------------. |
        | V .-IN----.                            | |
        '---+-------+--parameter-name--data-type-+-'
            +-OUT---+
            '-INOUT-'
>--+-------------------------+--*------------------------------->
   '-SPECIFIC--specific-name-'
   .-DYNAMIC RESULT SETS 0--------.     .-MODIFIES SQL DATA-.
>--+------------------------------+--*--+-------------------+--->
   '-DYNAMIC RESULT SETS--integer-'     +-CONTAINS SQL------+
                                        '-READS SQL DATA----'
      .-NOT DETERMINISTIC-.     .-CALLED ON NULL INPUT-.
>--*--+-------------------+--*--+----------------------+--*----->
      '-DETERMINISTIC-----'
   .-INHERIT SPECIAL REGISTERS-.     .-7 OLD SAVEPOINT LEVEL-.
>--+---------------------------+--*--+---------------------+---->
                                     '-7 NEW SAVEPOINT LEVEL-'
      .-LANGUAGE SQL-.     .-7 EXTERNAL ACTION----.
>--7 *--+--------------+--*--+--------------------+--*------------>
                           '-7 NO EXTERNAL ACTION-'
>--+------------------------------+--3 *-------------------------->
   '-3 PARAMETER CCSID--+-3 ASCII---+-'
                      '-3 UNICODE-'
>--| SQL-procedure-body |--------------------------------------><
SQL-procedure-body:
|--SQL-procedure-statement--------------------------------------|

Description
procedure-name
Names the procedure being defined. It is a qualified or unqualified name that designates a procedure. The unqualified form of procedure-name is an SQL identifier (with a maximum length of 128). In dynamic SQL statements, the CURRENT SCHEMA special register is used as a qualifier for an unqualified object name. In static SQL statements, the QUALIFIER precompile/bind option implicitly specifies the qualifier for unqualified object names. The qualified form is a schema-name followed by a period and an SQL identifier.
The name, including the implicit or explicit qualifiers, together with the number of parameters, must not identify a procedure described in the catalog (SQLSTATE 42723). The unqualified name, together with the number of parameters, is unique within its schema, but does not need to be unique across schemas.
If a two-part name is specified, the schema-name cannot begin with 'SYS'; otherwise, an error is returned (SQLSTATE 42939).
(IN | OUT | INOUT parameter-name data-type,...)
Identifies the parameters of the procedure, and specifies the mode, name, and data type of each parameter. One entry in the list must be specified for each parameter that the procedure will expect.
It is possible to register a procedure that has no parameters. In this case, the parentheses must still be coded, with no intervening data types. For example:
   CREATE PROCEDURE SUBWOOFER() ...
No two identically-named procedures within a schema are permitted to have exactly the same number of parameters. A duplicate signature raises an SQL error (SQLSTATE 42723).
For example, given the statements:
   CREATE PROCEDURE PART (IN NUMBER INT, OUT PART_NAME CHAR(35)) ...
   CREATE PROCEDURE PART (IN COST DECIMAL(5,3), OUT COUNT INT) ...
the second statement will fail because the number of parameters in the procedure is the same, even if the data types are not.
IN | OUT | INOUT
Specifies the mode of the parameter.
If an error is returned by the procedure, OUT parameters are undefined and INOUT parameters are unchanged.
IN
Identifies the parameter as an input parameter to the procedure. Any changes made to the parameter within the procedure are not available to the calling SQL application when control is returned. The default is IN.
OUT
Identifies the parameter as an output parameter for the procedure.
INOUT
Identifies the parameter as both an input and output parameter for the procedure.
parameter-name
Specifies the name of the parameter. The parameter name must be unique for the procedure (SQLSTATE 42734).
data-type
Specifies the data type of the parameter.
SQL data type specifications and abbreviations that can be specified in the data-type definition of a CREATE TABLE statement, and that have a correspondence in the language that is being used to write the procedure, may be specified.
1 LONG VARCHAR, LONG VARGRAPHIC, DATALINK, REFERENCE, and 1 user-defined structured types are not supported (SQLSTATE 429BB).
SPECIFIC specific-name
Provides a unique name for the instance of the procedure that is being defined. This specific name can be used when dropping the procedure or commenting on the procedure. It can never be used to invoke the procedure. The unqualified form of specific-name is an SQL identifier (with a maximum length of 18). The qualified form is a schema-name followed by a period and an SQL identifier. The name, including the implicit or explicit qualifier, must not identify another procedure instance that exists at the application server; otherwise an error (SQLSTATE 42710) is raised.
The specific-name can be the same as an existing procedure-name.
If no qualifier is specified, the qualifier that was used for procedure-name is used. If a qualifier is specified, it must be the same as the explicit or implicit qualifier for procedure-name, or an error (SQLSTATE 42882) is raised.
If specific-name is not specified, a unique name is generated by the database manager. The unique name is SQL followed by a character timestamp, SQLyymmddhhmmsshhn.
DYNAMIC RESULT SETS integer
Indicates the estimated upper bound of returned result sets for the procedure.
CONTAINS SQL, READS SQL DATA, MODIFIES SQL DATA
Indicates the level of data access for SQL statements included in the procedure.
CONTAINS SQL
Indicates that SQL statements that neither read nor modify SQL data can be executed by the procedure (SQLSTATE 38004 or 42985). Statements that are not supported in any procedure return a different error (SQLSTATE 38003 or 42985).
READS SQL DATA
Indicates that some SQL statements that do not modify SQL data can be included in the procedure (SQLSTATE 38002 or 42985). Statements that are not supported in any procedure return a different error (SQLSTATE 38003 or 42985).
MODIFIES SQL DATA
Indicates that the procedure can execute any SQL statement except statements that are not supported in procedures (SQLSTATE 38003 or 42985).
DETERMINISTIC or NOT DETERMINISTIC
This clause specifies whether the procedure always returns the same results for given argument values (DETERMINISTIC) or whether the procedure depends on some state values that affect the results (NOT DETERMINISTIC). That is, a DETERMINISTIC procedure must always return the same result from successive invocations with identical inputs.
This clause currently does not impact processing of the procedure.
CALLED ON NULL INPUT
CALLED ON NULL INPUT always applies to procedures. This means that the procedure is called regardless of whether any arguments are null. Any OUT or INOUT parameter can return a null value or a normal (non-null) value. Responsibility for testing for null argument values lies with the procedure.
INHERIT SPECIAL REGISTERS
This optional clause specifies that updatable special registers in the procedure will inherit their initial values from the environment of the invoking statement. For a routine invoked in a nested object (for example a trigger or view), the initial values are inherited from the runtime environment (not inherited from the object definition).
No changes to the special registers are passed back to the caller of the procedure.
Non-updatable special registers, such as the datetime special registers, reflect a property of the statement currently executing, and are therefore set to their default values.
7 7 OLD SAVEPOINT LEVEL or NEW SAVEPOINT LEVEL 7 Specifies whether or not this procedure establishes a 7 new savepoint level for savepoint names and effects. 7 OLD SAVEPOINT LEVEL is the default behavior. 7 For more information about savepoint levels, see the "Rules" 7 section in the description of the SAVEPOINT statement. 7 LANGUAGE SQL
This clause is used to specify that the procedure body is written in the SQL language. 7 7 EXTERNAL ACTION or NO EXTERNAL ACTION 7 Specifies whether the procedure takes some action that changes 7 the state of an object not managed by the database manager (EXTERNAL 7 ACTION), or not (NO EXTERNAL ACTION). 7 The default is EXTERNAL ACTION. 7 If NO EXTERNAL ACTION is specified, the system can use certain 7 optimizations that assume the procedure has no external impact. 7 3 3 PARAMETER CCSID 3 Specifies the encoding scheme to use for all string data 3 passed into and out of the procedure. 3 If the PARAMETER CCSID clause is not specified, the default is 3 PARAMETER CCSID UNICODE for Unicode databases, and PARAMETER CCSID 3 ASCII for all other databases. 3 3 3 ASCII 3 Specifies that string data is encoded in the database 3 code page. 3 If the database is a Unicode database, PARAMETER CCSID ASCII cannot 3 be specified (SQLSTATE 56031). 3 3 UNICODE 3 Specifies that character data is in UTF-8, and that graphic 3 data is in UCS-2. 3 If the database is not a Unicode database, PARAMETER CCSID UNICODE 3 cannot be specified (SQLSTATE 56031). 3 3 3 SQL-procedure-body
Specifies the SQL statement that is the body of the SQL procedure. Multiple SQL-procedure-statements can be specified within a procedure-compound-statement. See SQL-procedure-statement in the description of the Compound SQL (Procedure) statement.
7 7 Rules 7 7 A procedure that is called from within a dynamic compound 7 statement will execute as if it were created specifying NEW SAVEPOINT 7 LEVEL, even if OLD SAVEPOINT LEVEL was specified or defaulted to when 7 the procedure was created.
Notes
Creating a procedure with a schema name that does not already exist will result in the implicit creation of that schema, provided that the authorization ID of the statement has IMPLICIT_SCHEMA authority. The schema owner is SYSIBM. The CREATEIN privilege on the schema is granted to PUBLIC.
Privileges
The definer of a procedure always receives the EXECUTE privilege WITH GRANT OPTION on the procedure, as well as the right to drop the procedure.
Compatibilities
For compatibility with DB2 UDB for OS/390 and z/OS:
The following syntax is accepted as the default behavior:
ASUTIME NO LIMIT
COMMIT ON RETURN NO
NO COLLID
STAY RESIDENT NO
For compatibility with previous versions of DB2:
RESULT SETS can be specified in place of DYNAMIC RESULT SETS.
NULL CALL can be specified in place of CALLED ON NULL INPUT.
Examples
Example 1: Create an SQL procedure that returns the median staff salary. Return a result set containing the name, position, and salary of all employees who earn more than the median salary.
   CREATE PROCEDURE MEDIAN_RESULT_SET (OUT medianSalary DOUBLE)
     RESULT SETS 1
     LANGUAGE SQL
   BEGIN
     DECLARE v_numRecords INT DEFAULT 1;
     DECLARE v_counter INT DEFAULT 0;
     DECLARE c1 CURSOR FOR
       SELECT CAST(salary AS DOUBLE)
         FROM staff
         ORDER BY salary;
     DECLARE c2 CURSOR WITH RETURN FOR
       SELECT name, job, CAST(salary AS INTEGER)
         FROM staff
         WHERE salary > medianSalary
         ORDER BY salary;
     DECLARE EXIT HANDLER FOR NOT FOUND
       SET medianSalary = 6666;
     SET medianSalary = 0;
     SELECT COUNT(*) INTO v_numRecords
       FROM STAFF;
     OPEN c1;
     WHILE v_counter < (v_numRecords / 2 + 1)
     DO
       FETCH c1 INTO medianSalary;
       SET v_counter = v_counter + 1;
     END WHILE;
     CLOSE c1;
     OPEN c2;
   END
Related reference
SAVEPOINT statement
Compound SQL (Procedure) statement
SQL statements allowed in routines
Special registers
Related samples
SQL procedures
basecase.db2 -- To create the UPDATE_SALARY SQL procedure
nestcase.db2 -- To create the BUMP_SALARY SQL procedure
nestedsp.db2 -- To create the OUT_AVERAGE, OUT_MEDIAN and MAX_SALARY SQL procedures
rsultset.db2 -- To register and create the MEDIAN_RESULT_SET SQL procedure
This topic can be found in: SQL Reference, Volume 2.
 

 

分享到:
评论

相关推荐

    DB2 SQL存储过程语法官方权威指南

    ### DB2 SQL存储过程语法官方权威指南 #### 一、概述 DB2是IBM公司推出的一款关系型数据库管理系统,广泛应用于各种大型企业级应用中。其中,存储过程是DB2中一个非常重要的特性,它允许开发者在数据库内编写可重用...

    DB2 SQL存储过程语法官方权威指南(翻译)

    本篇将深入解析DB2 SQL存储过程的创建语法及其相关知识点。 1. **创建存储过程的语法** 创建存储过程的语句以`CREATE PROCEDURE`开头,接着是存储过程的名称,这是必须提供的。在DB2中,每个存储过程必须具有一个...

    db2SQL_Reference_1_950

    - **Schema**:在DB2中,schema是一个命名空间,用于组织和隔离数据库对象,如表格、视图和存储过程。每个schema都有一个所有者,并且可以包含多个用户的数据。 - **Tables**:表格是存储数据的基本单元。DB2支持...

    db2学习代码例子(代码为转载网上)

    4. `DB2 SQL存储过程语法官方权威指南(翻译).mht`:这个文件提供了DB2 SQL存储过程的官方语法参考,可能包括创建、修改和执行存储过程的步骤,以及各种内置函数和控制结构的用法。 5. `freelance graphics - ebu-...

    DB2 SQL Reference

    DB2 SQL Reference是一本详尽的指南,不仅介绍了SQL语言的基础语法,还深入讲解了DB2数据库中高级特性的使用方法,包括静态和动态SQL、CLI、JDBC、SQLJ、交互式SQL等。此外,它还详细阐述了数据库设计的核心概念,如...

    DB2_v105 官方中文参考手册(1)

    6. **DB2DevGettingStarted-db2axc1050.pdf**:开发人员入门指南,为初学者提供DB2开发的基础知识,包括安装、基本操作、数据类型、SQL语法等。 7. **DB2DevADO.NET-OLEDB-db2anc1050.pdf**:使用ADO.NET和OLE DB...

    IBM DB2 - SQL Reference for Cross-Platform Development

    - 学生和教育工作者:希望通过一个权威的资源学习和教授DB2 SQL。 #### 使用指南 本书包含多个章节,每个章节都针对不同的主题进行了详细的讲解。通过以下方式可以更高效地利用本书: - **查阅索引**:书中提供了...

    MongoDB权威指南.pdf-PostgreSQL_to_DB2_Porting_Guide.pdf

    2. SQL语法差异:尽管都遵循SQL标准,但具体的语法和函数可能存在差异,需要调整查询语句。 3. 事务处理策略:根据DB2的特点调整事务处理逻辑,确保事务的一致性。 4. 安全性和权限管理:迁移时需考虑用户和角色的...

    IBM DB2 730考试认证

    对于IT专业人士来说,获得这个认证能够提升其在数据库领域的专业形象,并为他们在企业环境中有效管理和维护IBM DB2数据库系统提供权威证明。 IBM DB2是全球广泛使用的数据库管理系统,特别适用于大型企业和关键任务...

    SQL语言教程&案例&相关项目资源.docx

    - 市面上有许多关于 SQL 的书籍,如《SQL 必知必会》、《SQL 权威指南》等,这些书籍详细介绍了 SQL 的基础知识和高级应用。 #### 二、SQL案例 **SQL案例** 是展示 SQL 语言在实际应用中如何解决问题的具体实例。...

Global site tag (gtag.js) - Google Analytics