DB2 Server for VSE & VM: SQL Reference


Chapter 6. Statements

This chapter contains syntax diagrams, semantic descriptions, rules, and examples of the use of the SQL statements listed in the following table.

Table 7. SQL Statements
SQL Statement Function Refer to Page
ACQUIRE DBSPACE Obtains and names a dbspace. ACQUIRE DBSPACE
ALLOCATE CURSOR Defines a cursor and associates it with a result set locator variable. ALLOCATE CURSOR
ALTER DBSPACE Alters the percentage of free space. Also alters the lock size of a PUBLIC dbspace. ALTER DBSPACE
ALTER PROCEDURE Alters the definition of an existing stored procedure. ALTER PROCEDURE
ALTER PSERVER Alters the definition of an existing stored procedure server. ALTER PSERVER
ALTER TABLE Adds a column to a table or manages referential constraints. ALTER TABLE
ASSOCIATE LOCATORS Obtains the RESULT SET LOCATOR value for each result set returned by a stored procedure. ASSOCIATE LOCATORS
BEGIN DECLARE SECTION Marks the beginning of a host variable declaration section. BEGIN DECLARE SECTION
CALL Invokes a stored procedure. CALL
CLOSE Closes a cursor. CLOSE
Extended CLOSE Closes a cursor defined by an Extended DECLARE CURSOR statement. Extended CLOSE
COMMENT ON Replaces or adds a comment to the description of a table, view, or column. COMMENT ON
COMMENT ON PROCEDURE Replaces or adds a comment to the description of a stored procedure identified. COMMENT ON PROCEDURE
COMMIT Terminates a logical unit of work and commits the database changes made by that logical unit of work. COMMIT
CONNECT Connects to an application server. CONNECT (for VM)
CREATE INDEX Defines an index on a table. CREATE INDEX
CREATE PACKAGE Creates a package. CREATE PACKAGE
CREATE PROCEDURE Defines a stored procedure. CREATE PROCEDURE
CREATE PSERVER Defines a stored procedure server. CREATE PSERVER
CREATE SYNONYM Defines an alternate name for a table or view. CREATE SYNONYM
CREATE TABLE Defines a table. CREATE TABLE
CREATE VIEW Defines a view of one or more tables or views. CREATE VIEW
DECLARE CURSOR Defines an SQL cursor. DECLARE CURSOR
Extended DECLARE CURSOR Defines a cursor that is to be associated with a statement that was prepared using an Extended PREPARE statement. Extended DECLARE CURSOR
DELETE Deletes zero or more rows from a table. DELETE
DESCRIBE Describes the result columns of a prepared statement. DESCRIBE
Extended DESCRIBE Describes the result columns of a SELECT statement that was prepared using an Extended PREPARE statement. Extended DESCRIBE
DESCRIBE CURSOR Obtains information about the result set that is associated with the cursor and puts that information into a descriptor. DESCRIBE CURSOR
DESCRIBE PROCEDURE Obtains information about the result sets returned by a stored procedure and puts that information into a descriptor. DESCRIBE PROCEDURE
DROP Deletes a dbspace, index, package. synonym, table, or view DROP
DROP PROCEDURE Deletes the definition of a stored procedure. DROP PROCEDURE
DROP PSERVER Deletes the definition of a stored procedure server. DROP PSERVER
DROP STATEMENT Deletes a statement from a package created with CREATE PACKAGE. DROP STATEMENT
END DECLARE SECTION Marks the end of a host variable declaration section. END DECLARE SECTION
EXECUTE Executes a prepared SQL statement. EXECUTE
Extended EXECUTE Executes an SQL statement prepared using an Extended PREPARE statement. Extended EXECUTE
EXECUTE IMMEDIATE Prepares and executes an SQL statement. EXECUTE IMMEDIATE
EXPLAIN Obtains information about the structure and execution performance of a DELETE, INSERT, UPDATE, or SELECT statement. EXPLAIN
FETCH Assigns values of a row of a result table to host variables. FETCH
Extended FETCH Assigns values of a row in a result table to host variables using a cursor defined by an Extended DECLARE CURSOR statement. Extended FETCH
GRANT (Package Privileges) Grants privilege to execute statements in a package GRANT (Package Privileges)
GRANT (System Authorities) Grants system authorities. GRANT (System Authorities)
GRANT (Table Privileges) Grants privileges on a table or view. GRANT (Table Privileges)
INCLUDE Inserts declarations into a source program. INCLUDE
INSERT Inserts zero or more rows into a table. INSERT
LABEL ON Replaces or adds a label on the description of a table, view, or column. LABEL ON
LOCK DBSPACE Either prevents concurrent processes from changing a dbspace or prevents concurrent processes from using a dbspace. LOCK DBSPACE
LOCK TABLE Either prevents concurrent processes from changing a table or prevents concurrent processes from using a table. LOCK TABLE
OPEN Opens a cursor. OPEN
Extended OPEN Opens a cursor defined by an Extended DECLARE CURSOR statement. Extended OPEN
PREPARE Prepares an SQL statement (with optional parameters) for execution within the same logical unit of work. PREPARE
Extended PREPARE Prepares an SQL statement into a package created with CREATE PACKAGE. Extended PREPARE
PUT Inserts (a row of) data into a table. PUT
Extended PUT Inserts (a row of) data into a table using a cursor defined by an Extended DECLARE CURSOR statement. Extended PUT
REVOKE (Package Privileges) Revokes the privilege to execute statements in a package. REVOKE (Package Privileges)
REVOKE (System Authorities) Revokes system authorities. REVOKE (System Authorities)
REVOKE (Table Privileges) Revokes privileges on a table or view. REVOKE (Table Privileges)
ROLLBACK Terminates a logical unit of work and backs out the database changes made by that unit of work. ROLLBACK
SELECT INTO Specifies a result table of no more than one row and assigns the values to host variables. SELECT INTO
UPDATE Updates the values of one or more columns in zero or more rows of a table. UPDATE
UPDATE STATISTICS Update statistics on tables and indexes in system catalogs. UPDATE STATISTICS
WHENEVER Defines actions to be taken on the basis of SQL return codes. WHENEVER


How SQL Statements Are Invoked

The SQL statements described in this chapter are classified as executable or nonexecutable. The Invocation section in the description of each statement indicates whether the statement is executable.

An executable statement can be invoked in three ways:

Depending on the statement, you can use some or all of these methods. The Invocation section in the description of each statement tells you which methods can be used.

A nonexecutable statement can only be embedded in an application program.

In addition to the statements described in this chapter, there is one more SQL statement construct: the select-statement. (See select-statement.) It is not included in this chapter because it is used differently from other statements.

A select-statement can be invoked in three ways:

The first two methods are called, respectively, the static and the dynamic invocation of select-statement.

The different methods of invoking an SQL statement are discussed below in more detail. For each method, the discussion includes the mechanism of execution, interaction with host variables, and testing if the execution was successful.

Embedding a Statement in an Application Program

You can include SQL statements in a source program that will be submitted to the preprocessor. Such statements are said to be embedded in the program. An embedded statement can be placed where a similar host language statement is allowed in the program. You must precede each embedded statement with EXEC SQL.

Executable statements

An executable statement embedded in an application program is run every time a statement of the host language would be processed if specified in the same place. (Thus, for example, a statement within a loop is run every time the loop is processed, and a statement within a conditional construct is run only when the condition is satisfied.)

An embedded statement can contain references to host variables. A host variable referenced in this way can be used in two ways:

In particular, all references to host variables in expressions and predicates are effectively replaced by current values of the variables, that is, the variables are used as input. The treatment of other references is described individually for each statement.

All executable statements should be followed by a test of an SQL return code (see SQL Return Codes). Alternatively, you can use the WHENEVER statement (which is itself nonexecutable) to change the flow of control immediately after the execution of an embedded statement.

If the program is prepared with the NOEXIST option (see the DB2 Server for VSE & VM Application Programming manual), then objects referenced in SQL statements need not exist when the statements are prepared.

Nonexecutable statements

An embedded nonexecutable statement is processed only by the preprocessor. The preprocessor reports any errors encountered in the statement. The statement is never processed, and acts as a no-operation if placed among executable statements of the application program. Therefore, you should not follow such statements by a test of an SQL return code.

Dynamic Preparation and Execution

Your application program can dynamically build an SQL statement in the form of a character string placed in a host variable. In general, the statement is built from some data available to the program (for example, input from a terminal). The statement so constructed can be prepared for execution by means of the (embedded) statement PREPARE and processed by means of the (embedded) statement EXECUTE. Alternatively, you can use the (embedded) statement EXECUTE IMMEDIATE to prepare and process a statement in one step.

A statement that is going to be dynamically prepared must not contain references to host variables. It can instead contain parameter markers. (See PREPARE for rules concerning the parameter markers.) When the prepared statement is processed, the parameter markers are effectively replaced by current values of the host variables specified in the EXECUTE statement. (See EXECUTE for rules concerning this replacement.) After prepared, a statement can be processed several times with different values of host variables. Note that parameter markers are not allowed in EXECUTE IMMEDIATE.

The successful or unsuccessful execution of the statement is indicated by the setting of an SQL return code in the SQLCA after the EXECUTE (or EXECUTE IMMEDIATE) statement. You should check the SQL return code as described above for embedded statements. See SQL Return Codes for more information.

Static Invocation of a select-statement

You can include a select-statement as a part of the (nonexecutable) statement DECLARE CURSOR. Such a statement is processed every time you open the cursor by means of the (embedded) statement OPEN. After the cursor is open, you can retrieve the result table a row at a time by successive executions of the FETCH statement.

The select-statement used in this way may contain references to host variables. These references are effectively replaced by the values that the variables have at the moment of executing OPEN.

Dynamic Invocation of a select-statement

Your application program can dynamically build a select-statement in the form of a character string placed in a host variable. In general, the statement is built from some data available to the program (for example, a query obtained from a terminal). The statement so constructed can be prepared for execution by means of the (embedded) statement PREPARE, and referenced by a (nonexecutable) statement DECLARE CURSOR. The statement is then processed every time you open the cursor by means of the (embedded) statement OPEN. After the cursor is open, you can retrieve the result table one row at a time by successive executions of the FETCH statement.

The select-statement used in that way must not contain references to host variables. It can instead contain parameter markers. (See PREPARE for rules concerning the parameter markers.) The parameter markers are effectively replaced by the values of the host variables specified in the OPEN statement. (See OPEN for rules concerning this replacement.)

Interactive Invocation

A capability for entering SQL statements from a terminal is part of the architecture of the database manager. This product provides ISQL and the Database Services utility for this facility. An associated product, Query Management Facility (QMF), also provides interactive access to DB2 Server for VSE & VM databases. A statement entered in this way is said to be issued interactively. See the DB2 Server for VSE & VM Interactive SQL Guide and Reference manual and the DB2 Server for VSE & VM Database Services Utility manual for more information and examples.

A statement issued interactively must be an executable statement that does not contain parameter markers or references to host variables. These make sense only in the context of an application program.


SQL Return Codes

An application program containing executable SQL statements must either provide a structure named SQLCA or a stand-alone integer variable named SQLCODE (SQLCOD in FORTRAN and RPG). An SQLCA is provided automatically in REXX and RPG. In other languages, an SQLCA can be obtained by using the INCLUDE SQLCA statement. INCLUDE SQLCA must not be used if a stand-alone SQLCODE is provided.

The SQLCA includes an integer variable named SQLCODE (SQLCOD in FORTRAN and RPG). The option of providing a stand-alone SQLCODE instead of an SQLCA allows for conformance with the ISO/ANSI SQL standard. This option can be requested with either the STDSQL(89) or NOSQLCA preprocessor option as described in the DB2 Server for VSE & VM Application Programming manual.

SQLCODE

Regardless of whether the application program provides an SQLCA or a stand-alone variable, SQLCODE is set by the database manager after each SQL statement is processed. All IBM database managers conform to the ISO/ANSI SQL standard, as follows:

The meaning of SQLCODE values other than 0 and 100 is usually product-specific.

SQLSTATE

SQLSTATE is also set by the database manager after execution of each SQL statement. Thus, application programs can check the execution of SQL statements by testing SQLSTATE instead of SQLCODE. SQLSTATE (SQLSTT in FORTRAN and RPG) is a character string variable in the SQLCA.

SQLSTATE provides application programs with common codes for common error conditions. Furthermore, SQLSTATE is designed so that application programs can test for specific errors or classes of errors. The coding scheme is the same for all database managers and is based on the proposed ISO/ANSI SQL2 standard. See "SQLSTATEs" in the DB2 Server for VM Messages and Codes or the DB2 Server for VSE Messages and Codes manual for more information and a complete list of the possible values of SQLSTATE.


SQL Comments

Static SQL statements can include host language or SQL comments. SQL comments are introduced by two hyphens.

These rules apply to the use of SQL comments:

For host language rules regarding the use of SQL comments, see the DB2 Server for VSE & VM Application Programming manual.

Example

This example shows how to include comments in a statement:

  CREATE VIEW PRJ_MAXPER -- projects with most support personnel
    AS SELECT PROJNO, PROJNAME -- number and name of project
    FROM PROJECT
    WHERE DEPTNO = 'E21' -- systems support dept code
    AND PRSTAFF > 1

ACQUIRE DBSPACE

The ACQUIRE DBSPACE statement causes the database manager to find and name an available dbspace.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

Syntax



>>-ACQUIRE----+-PUBLIC--+--DBSPACE NAMED--dbspace_name---------->
              '-PRIVATE-'
 
>-----+-------------------------------------------+------------><
      |    .-,-----------------------------.      |
      |    V    (1)                        |      |
      '-(----+--------------------------+--+---)--'
             |             .-8-------.  |
             +-NHEADER = --+-integer-+--+
             |           .-128-----.    |
             +-PAGES = --+-integer-+----+
             |              .-33------. |
             +-PCTINDEX = --+-integer-+-+
             |             .-15------.  |
             +-PCTFREE = --+-integer-+--+
             |          .-PAGE----.     |
             +-LOCK = --+-DBSPACE-+-----+
             |          '-ROW-----'     |
             '-STORPOOL = --integer-----'
 


Notes:



  1. If any of these clauses is specified more than once, the value with the
    first specification is used.


Description

PUBLIC/PRIVATE
Is the type of dbspace requested. If the dbspace is PUBLIC, its owner becomes PUBLIC; if the type is PRIVATE, its owner becomes the authorization ID of the statement.

NAMED dbspace-name
Provides a name for the dbspace. The name must be a valid SQL identifier. It must be unique within all the dbspaces owned by the same user, but may duplicate the name of a dbspace owned by another user.

If the dbspace name of a private dbspace is qualified, the qualifier is the owner of the dbspace. Otherwise, the authorization ID of the statement is the owner of the dbspace. The owner has all privileges on the dbspace. The privileges can be granted by the owner and cannot be revoked from the owner.

If the dbspace name of a public dbspace is qualified, the qualifier must be "PUBLIC".

NHEADER
Is the number of 4096-byte logical pages in the dbspace that the database manager reserves for header pages. Header pages record information about the contents of the dbspace. NHEADER cannot be larger than eight pages.

PAGES
Is the minimum number of 4096-byte logical pages required for this dbspace. The database manager determines the page number by rounding the number you specify to the next higher multiple of 128.

PCTINDEX
Is the percentage of all pages in the dbspace that the database manager is to reserve for the construction of indexes.

PCTFREE
Is the percentage of space on each page that the database manager is to keep free when data is inserted into the dbspace.

LOCK
Is the lock size, applicable to public dbspaces only. The lock size determines the extent of locking that the database manager acquires when a user reads or updates data. If ROW is specified, only a row in the table is locked; PAGE or DBSPACE cause the smallest lockable unit to be a page (4096 bytes) or the dbspace, respectively.

STORPOOL
Is the storage pool number. This parameter tells the database manager to acquire the dbspace from a specified storage pool. If a dbspace of the specified type and size is not available in the storage pool, the ACQUIRE DBSPACE is not successful and the database manager returns an error. If STORPOOL is not specified, the database manager acquires a dbspace of the correct size and type from any recoverable storage pool. For more information, see the DB2 Server for VM System Administration or DB2 Server for VSE System Administration manual.

Example

Acquire a private dbspace in storage pool number 3 and call it FCPSPACE. Leave 25% of the space free on each page.

  ACQUIRE PRIVATE DBSPACE NAMED FCPSPACE
    (STORPOOL=3, PCTFREE=25)

|ALLOCATE CURSOR

| |

|The ALLOCATE CURSOR statement defines a cursor and associates it with a |result set locator variable.

|Invocation

|This statement can be embedded in an application program. It is an |executable statement that can be dynamically prepared. It cannot by |issued interactively.

|Authorization

|None required.

|Syntax


|

>>-ALLOCATE--cursor-name--CURSOR FOR RESULT SET--rs-locator-variable-->
 
>--------------------------------------------------------------><
 

|Description |

|cursor-name |
|Identifies a cursor name, which must be unique within the logical unit of |work in which it is used. It is an ordinary identifier.

|CURSOR FOR RESULT SET rs-locator-variable
|Identifies a result set locator variable that has been declared in the |application program according to the rules for declaring result set locator |variables. The result set locator variable must contain a valid result |set locator value, as is returned by the ASSOCIATE LOCATORS or DESCRIBE |PROCEDURE SQL statement. |

|Notes |

  1. |Dynamically prepared ALLOCATE CURSOR statements:

    |One restriction is that a statement identifier cannot be used for an |ALLOCATE CURSOR statement if the same statement identifier has been used for a |DECLARE CURSOR statement. For example, the following SQL statements are |not valid because the PREPARE statement uses STMT1 as an identifier for the |ALLOCATE CURSOR statement when it has already been used for a DECLARE CURSOR |statement:

    |DECLARE C1 CURSOR FOR STMT1;
    | 
    |PREPARE STMT1 FROM
    |    'ALLOCATE C2 CURSOR FOR RESULT SET ?'; INVALID

    |If an ALLOCATE CURSOR statement is dynamically prepared, the DYNALC prep |option must be used for the preprocessor to successfully process any FETCH |statements issued against the allocated cursor. If the prep option is |not used, the preprocessor returns SQLCODE -504 for these FETCH statements |because the cursor was not identified by the prep.

  2. |Rules for using an allocated cursor:

    |The following rules apply when you use an allocated cursor: |

  3. |Mortality of an allocated cursor:

    |A rollback and an implicit and explicit close will destroy allocated |cursors. A commit destroys allocated cursors that are not defined WITH |HOLD by the stored procedure. However, note that DB2 Server for VSE |& VM does not support CURSOR WITH HOLD. Destroying an allocated |cursor closes the associated cursor in the stored procedure.

  4. |For the ALLOCATE CURSOR statement to be successful, the application must |be connected to the site at which the stored procedure was executed. |

|Examples

|

|The statement in the following example is assumed to be in a PL/I |program.

|Define and associate cursor C1 with the result set locator variable |:loc1 and the related result set returned by the stored procedure:

|   EXEC SQL ALLOCATE C1 CURSOR FOR RESULT SET :loc1
| |

ALTER DBSPACE

The ALTER DBSPACE statement lets you change the amount of free space that the database manager reserves on each data page, and lets you change the type of a lock on a public dbspace.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

Syntax



>>-ALTER DBSPACE--dbspace_name---------------------------------->
 
        .-,----------------------------------.
        V   (1)                              |
>----(------------+-PCTFREE = integer-----+--+---)-------------><
                  '-LOCK =----+-PAGE----+-'
                              +-DBSPACE-+
                              '-ROW-----'
 


Notes:



  1. If either of these clauses is specified more than once, the value with the
    first specification is used.


Description

dbspace_name
Identifies the dbspace to be changed. It must be a dbspace that exists at the application server.

PCTFREE
Is the percentage of space on each page that the database manager is to keep empty when inserting data into the dbspace's tables. A common practice is to set PCTFREE to a higher value when a dbspace is acquired, load the data, and create an index defined in the same order as the data was loaded. After this process is complete, the PCTFREE is lowered. Some or all of the free space is now available for inserts. The judicious use of reserved free space may result in a more favorable placement of data on pages and, therefore, improve access time.

LOCK
Alters the lock size of a public dbspace. The valid lock sizes are DBSPACE, PAGE, and ROW. If DBSPACE is specified, the system locks the whole dbspace. Page causes the smallest lockable unit to be a page (4096 bytes); ROW causes this unit to be a row.

Examples

Example 1

Alter your private dbspace named FCPSPACE so that no space is reserved on any of the pages.

  ALTER DBSPACE FCPSPACE  (PCTFREE=0)

Example 2

Alter a public dbspace named SPACE so that the pages are locked and the amount of free space is reduced to 3%.

  ALTER DBSPACE PUBLIC.SPACE
    (PCTFREE=3, LOCK=PAGE)

ALTER PROCEDURE

The ALTER PROCEDURE statement is used to alter the definition of an existing stored procedure. It updates the catalog and the corresponding cached information.

The STOP PROC command must be issued with the REJECT option before the ALTER PROCEDURE statement will be accepted.

Invocation

This statement can be issued from an application program or interactively. It is an executable statement that can be dynamically prepared.

Authorization

The issuer of the ALTER PROCEDURE must have DBA authority.

Syntax

ALTER PROCEDURE
 
>>-ALTER PROCEDURE---procedure-name----+-----------------+------>
                                       '-AUTHID--authid--'
 
      .-,-----------------.
      V                   |  (1)
>--------+-------------+--+------------------------------------><
         '-| options |-'
 

Notes:

  1. One or more clauses may be specified, however each clause may be specified at most once.

 
options
 
|--+-LANGUAGE-+-ASSEMBLE-+---------------------------------+----|
   |          +-C--------+                                 |
   |          +-COBOL----+                                 |
   |          '-PLI------'                                 |
   +-EXTERNAL NAME--external-program-name------------------+
   +-SERVER GROUP--+-------------------+-------------------+
   |               '-server-group-name-'                   |
   +-+-DEFAULT SERVER GROUP YES-+--------------------------+
   | '-DEFAULT SERVER GROUP NO--'                          |
   |                                   (2)                 |
   +---+-----------------+---+-GENERAL-----------------+---+
   |   '-PARAMETER STYLE-'   |                    (3)  |   |
   |                         '-GENERAL WITH NULLS------'   |
   +---STAY RESIDENT-+-NO--+-------------------------------+
   |                 '-YES-'                               |
   +-+-PROGRAM TYPE MAIN-----+-----------------------------+
   | |                  (4)  |                             |
   | '-PROGRAM TYPE SUB------'                             |
   +-RUN OPTIONS--run-time-options-------------------------+
   +-RESULT--+-SET--+---integer----------------------------+
   |         '-SETS-'                                      |
   +-COMMIT ON RETURN-+-NO--+------------------------------+
   |                  '-YES-'                              |
   |                     (1)  (5)                          |
   +-+-NOT DETERMINISTIC-----------+-----------------------+
   | |               (1)  (6)      |                       |
   | '-DETERMINISTIC---------------'                       |
   |                (1)                                    |
   +-+-CONTAINS SQL-----------+----------------------------+
   | |        (1)             |                            |
   | +-NO SQL-----------------+                            |
   | |                (1)     |                            |
   | +-READS SQL DATA---------+                            |
   | |                   (1)  |                            |
   | '-MODIFIES SQL DATA------'                            |
   |             (1)                                       |
   +-+-NO COLLID-------------------+-----------------------+
   | |                       (1)   |                       |
   | '-COLLID--collection-id-------'                       |
   |                   (1)                                 |
   +-+-WLM ENVIRONMENT------+-name-----+-+-----------------+
   | |                      '-(name,*)-' |                 |
   | |                    (1)            |                 |
   | '-NO WLM ENVIRONMENT----------------'                 |
   |         (1)                                           |
   +-ASUTIME-------+-NO LIMIT--------+---------------------+
   |               '-LIMIT--integer--'                     |
   |    (1)                                                |
   +-+-------------------------------+---------------------+
   | '-EXTERNAL SECURITY-+-DB2-----+-'                     |
   |                     +-USER----+                       |
   |                     '-DEFINER-'                       |
   |             (1)                                       |
   '-+-NO DBINFO------+------------------------------------'
     |        (1)     |
     '-DBINFO---------'
 

Notes:

  1. This parameter is included for compatibility with the DB2 family. If specified, it is ignored.

  2. SIMPLE CALL may be used as an alternative to GENERAL. This is for compatibility within the DB2 family.

  3. SIMPLE CALL WITH NULLS may be used as an alternative to GENERAL WITH NULLS. This is for compatibility within the DB2 family.

  4. Currently, DB2 Server for VSE & VM supports stored procedures written as main programs only.

  5. VARIANT may be specified as an alternative to NOT DETERMINISTIC. This is for compatibility within the DB2 family.

  6. NOT VARIANT may be specified as an alternative to DETERMINISTIC. This is for compatibility within the DB2 family.

Only the parameters that are meaningful to DB2 Server for VSE & VM are described here. If a parameter is not specified on the ALTER PROCEDURE statement, its value is unchanged.

Description

procedure-name
Names the stored procedure. For DB2 Server for VSE & VM, the name must be an ordinary identifier of 18 characters or less.

authid
The authorization ID for the stored procedure. The authid must be an ordinary identifier of 8 characters or less. If specified, then only the version of procedure-name that is accessible only by authid will be altered.

LANGUAGE
Specifies the programming language used to create the stored procedure. All stored procedure programs must be designed to run in the IBM Language Environment.

ASSEMBLE
Specifies that the stored procedure is written in Assembler.

C
Specifies that the stored procedure is written in C.

COBOL
Specifies that the stored procedure is written in COBOL.

PLI
Specifies that the stored procedure is written in PLI.

EXTERNAL NAME external-program-name
Identifies the load module or phase associated with the stored procedure. The external-program-name must be an ordinary identifier of 8 characters or less. The load module or phase does not need to exist when the ALTER PROCEDURE statement is issued. However, when a CALL for the stored procedure is issued, the load module must exist and be accessible to the stored procedure server.

SERVER GROUP server-group-name
Identifies the group of stored procedure servers in which this stored procedure will run. If specified, server-group-name must be an ordinary identifier of 18 characters or less. server-group-name must be defined in SYSTEM.SYSPSERVERS.

The SERVER GROUP clause can be specified without a server group name. This provides the ability to take a stored procedure out of a named group and move it to the default group. If server-group-name is not specified, the stored procedure must be able to run in the default group. The DEFAULT SERVER GROUP clause determines whether the stored procedure can run in the default stored procedure server group.

DEFAULT SERVER GROUP
Specifies whether the stored procedure can run in the default server group.

YES
The stored procedure can run in the default server group.

NO
The stored procedure cannot run in the default server group. If NO is specified, the SERVER GROUP clause must have been provided on the CREATE PROCEDURE statement, or it must be provided on the ALTER PROCEDURE statement.

PARAMETER STYLE
Identifies the linkage convention used to pass parameters to the stored procedure. All of the linkage conventions provide arguments to the stored procedure containing the parameters specified on the SQL CALL statement. See the DB2 Server for VSE & VM Database Administration manual for more information. The following parameter styles options are valid for DB2 Server for VSE & VM:

GENERAL
If the GENERAL linkage convention is used:
  • the SQL CALL statement must provide a parameter for each parameter expected by the stored procedure
  • input parameters cannot be null
  • nulls can be passed for output parameters only
  • the stored procedure cannot return nulls for output parameters

GENERAL WITH NULLS
If the GENERAL WITH NULLS linkage convention is used:
  • the SQL CALL statement must provide a parameter for each parameter expected by the stored procedure. When the database manager invokes the stored procedure, it sends it the parameters specified on the SQL CALL statement, as well as an array of indicator variables (with one indicator variable for each parameter). The stored procedure must contain a declaration for this array.
  • input parameters can be null. This is achieved through the use of indicator variables, or by specifying the keyword null.
  • the stored procedure can return nulls for output parameters, by using indicator variables.

STAY RESIDENT
Specifies whether the stored procedure load module or phase remains loaded in memory after the stored procedure ends. Possible values are:

NO
The load module or phase is deleted from memory after the stored procedure ends.

YES
The load module or phase remains loaded in memory after the stored procedure ends.

PROGRAM TYPE
Specifies whether the stored procedure runs as a MAIN routine or as a SUB routine. Currently, DB2 Server for VSE & VM supports only stored procedures written as MAIN routines. If PROGRAM TYPE SUB is specified, DB2 Server for VSE & VM will override it with PROGRAM TYPE MAIN.

RUN OPTIONS
Specifies the Language Environment run-time options to be passed to the stored procedure. The options must be specified as a character string up to 254 bytes enclosed in single quotation marks. If this option is not specified, or an empty string is passed, then DB2 Server for VSE & VM passes no run-time options to the Language Environment, and Language Environment uses its installation defaults. Note that DB2 Server for VSE & VM does not do any checking of the options provided. For a complete description of Language Environment run-time options, see Language Environment for MVS & VM Programming Reference.

RESULT SETS or RESULT SET
Specifies the maximum number of query result sets that can be returned by this stored procedure. The largest value that can be specified is 32767.

COMMIT ON RETURN
Indicates whether the unit of work should be committed immediately upon return from the stored procedure.

NO
The database manager should not issue COMMIT when the stored procedure returns.

YES
The database manager should issue COMMIT when the stored procedure returns when the following statements are true:
  • The SQLCODE returned by the CALL statement is not negative
  • The stored procedure is not in a must abort state

The COMMIT operation includes the work performed by the calling application as well as the stored procedure. Any cursors that are open when the COMMIT occurs will be closed during COMMIT processing.

Examples

Example 1

   ALTER PROCEDURE MYPROC STAY RESIDENT NO

ALTER PSERVER

The ALTER PSERVER statement alters the definition of an existing stored procedure server.

The STOP PSERVER command must be issued with the NOIMPLICIT option before the ALTER PSERVER statement will be accepted.

Invocation

This statement can be issued from an application program or interactively. It is an executable statement that can be dynamically prepared.

Authorization

The issuer of the ALTER PSERVER statement must have DBA authority.

Syntax



>>-ALTER PSERVER------------------------------------------------>
 
                        .-,------------------------------.
                        V    (1)                         |
>-----procedure-server----+---------------------------+--+-----><
                          +-GROUP--+------------+-----+
                          |        '-group-name-'     |
                          +-+-AUTOSTART NO--+---------+
                          | '-AUTOSTART YES-'         |
                          '-DESCRIPTION--description--'
 


Notes:


  1. One or more clauses may be specified, however each clause may be specified
    at most once.


Description

procedure-server
The name of the stored procedure server. This must be an ordinary identifier of 8 characters or less.

GROUP
The name of the group that this stored procedure server will be in after the ALTER PSERVER statement has been executed. If a group name is specified, it must be an ordinary identifier of 1 to 18 characters. If the GROUP clause is specified without group-name, the stored procedure server will be put in the default group.

group-name
The name of the stored procedure group. It cannot be any of the following:
GROUP
IMPLICIT
NOIMPLICIT
NORMAL
QUICK

AUTOSTART
Determines whether the database manager will issue a START PSERVER command for this stored procedure server when the database is started.

NO
START PSERVER will not be issued when the database is started.

YES
START PSERVER will be issued when the database is started.

DESCRIPTION
This field provides the database administrator with a place to provide information about this stored procedure server, such as virtual storage requirements, other servers in the group, and so on. Description can be up to 254 characters and must be enclosed in single quotation marks.

Examples

Example 1

   ALTER PSERVER SRV1 GROUP GRP2, AUTOSTART NO

ALTER TABLE

The ALTER TABLE statement adds a single column to an existing table, and adds, drops, activates, or deactivates primary and foreign keys.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

To create, drop, activate, or deactivate a foreign key, the authorization ID of the statement must also hold at least one of the following on the parent table:

To drop, activate, or deactivate a primary key, the authorization ID of the statement must also hold at least one of the following on each table that has a foreign key referencing the primary key that is being dropped.

Syntax



>>-ALTER TABLE--table_name-------------------------------------->
 
>-----+-ADD--| column-definition-block |--------------+--------><
      | .-ADD-.                                       |
      +-+-----+--+-| primary-key-block |------------+-+
      |          +-| referential-constraint-block |-+ |
      |          '-| unique-block |-----------------' |
      +-DROP--+-PRIMARY KEY-------------------+-------+
      |       +-FOREIGN KEY--constraint_name--+       |
      |       '-UNIQUE--constraint_name-------'       |
      +-ACTIVATE--+-ALL---------------------------+---+
      |           +-PRIMARY KEY-------------------+   |
      |           +-FOREIGN KEY--constraint_name--+   |
      |           '-UNIQUE--constraint_name-------'   |
      +-DEACTIVATE--+-ALL---------------------------+-+
      |             +-PRIMARY KEY-------------------+ |
      |             +-FOREIGN KEY--constraint_name--+ |
      |             '-UNIQUE--constraint_name-------' |
      '-DATA CAPTURE--+-NONE----+---------------------'
                      '-CHANGES-'
 
 
column-definition-block
 
|--column_name-------------------------------------------------->
 
>-----| data-type |--+-----------------------------+------------|
                     |  (1)                        |
                     '--------| fieldproc-block |--'
 
data-type
 
|---+-INTeger--------------------------------------------------+->
    +-SMALLINT-------------------------------------------------+
    |          .-(53)------.                                   |
    +-+-FLOAT--+-----------+-+---------------------------------+
    | |        '-(integer)-' |                                 |
    | +-REAL-----------------+                                 |
    | '-DOUBLE PRECISION-----'                                 |
    |                .-(5,0)------------------------.          |
    +--+-DECimal-+---+------------------------------+----------+
    |  '-NUMERIC-'   '-(--integer--+----------+--)--'          |
    |                              '-,integer-'                |
    |               .-(1)-------.                              |
    +--+-CHARacter--+-----------+-+---+-----------------+------+
    |  |            '-(integer)-' |   |  (1)            |      |
    |  +-VARCHAR--(integer)-------+   +-----------------+      |
    |  '-LONG VARCHAR-------------'   +-FOR SBCS DATA---+      |
    |                                 +-FOR MIXED DATA--+      |
    |                                 +-FOR BIT DATA----+      |
    |                                 '-CCSID--integer--'      |
    |             .-(1)-------.                                |
    +--+-GRAPHIC--+-----------+-+---+------------------------+-+
    |  |          '-(integer)-' |   |  (1)                   | |
    |  +-VARGRAPHIC--(integer)--+   '--------CCSID--integer--' |
    |  '-LONG VARGRAPHIC--------'                              |
    |                                                          |
    +-DATE-----------------------------------------------------+
    +-TIME-----------------------------------------------------+
    '-TIMESTAMP------------------------------------------------'
 
>---------------------------------------------------------------|
 


Notes:



  1. These clauses may be specified in any order.




 
fieldproc-block
 
|--FIELDPROC--program_name----+-------------------------+-------|
                              |    .-,-----------.      |
                              |    V             |      |
                              '-(-----constant---+---)--'
 
 
primary-key-block
 
                    .-,------------------------------.
                    V   (1)                .-ASC--.  |
|--PRIMARY KEY---(------------column_name--+------+--+---)------>
                                           '-DESC-'
 
      .-PCTFREE = 10------.
>-----+-------------------+-------------------------------------|
      '-PCTFREE = integer-'
 


Notes:



  1. There can be up to 16 columns in a primary key.


 
referential-constraint-block
 
                                          .-,--------------.
                                          V                |
|--FOREIGN KEY--+-----------------+--(-------column_name---+---->
                '-constraint_name-'
 
>----)--REFERENCES--table_name----+---------------------------+-|
                                  |            .-RESTRICT--.  |
                                  '-ON DELETE--+-CASCADE---+--'
                                               '-SET NULL--'
 
 
unique-block
 
|--UNIQUE--+-----------------+---------------------------------->
           '-constraint_name-'
 
        .-,------------------------------.
        V   (1)                .-ASC--.  |
>----(------------column_name--+------+--+---)------------------>
                               '-DESC-'
 
      .-PCTFREE = 10------.
>-----+-------------------+-------------------------------------|
      '-PCTFREE = integer-'
 


Notes:



  1. There can be up to 16 columns on a unique constraint.


Description

table_name
Identifies the table to be changed. It must be a table that exists at the application server and must not be a view or a catalog table. If the table_name is qualified, the qualifier is the owner of the table. Otherwise, the authorization ID of the statement is the owner of the table.

ADD
Adds a column to the table. All column values are NULL and the column is the last table column on the rightmost side. That is, if initially there are n columns, the added column is column n+1. The value of n cannot be greater than 254.

Adding the new column must not make the total byte count of all columns exceed the maximum record size of approximately 4072 bytes. For more information, see Notes.

column_definition_block

column_name
Names the column to be added to the table. The name cannot already be used by an existing column of the table.

data_type
Is one of the data types in the descriptions listed under CREATE TABLE.

fieldproc_block

FIELDPROC program_name
Names a field procedure for the column. A field procedure may be used only with a short string column. If FIELDPROC is omitted, the column has no field procedure.

constant
Is a parameter passed to the field procedure when the ALTER TABLE statement invokes it. A parameter list is optional. The number of parameters and the data type of each are determined by the field procedure. The maximum length of the parameter list is 254 bytes, including commas, but excluding insignificant blanks and excluding the delimiting parentheses after blank compression takes place.

primary_key_block

PRIMARY KEY
Is a set of column values in the table that enforces a unique constraint. Only one primary key is allowed in a parent table. Primary key values must be unique and must be defined as NOT NULL.

Defining a primary key on a table sets up the table to be referenced by another table's foreign key to establish a referential constraint.

column_name
Identifies the column or columns that comprise the primary keys. Each column_name must be an unqualified name that identifies a column of the table. No column in a primary key can contain a long string. The same column cannot be specified more than once.

ASC
Creates the primary key such that the values from this column are arranged in ascending order. This is the default.

DESC
Creates the primary key such that the values from this column are arranged in descending order.

PCTFREE
Is the percentage of space in each index page reserved for later insertions and updates of primary keys. The integer may range from 0 to 99, but for practical purposes should not exceed 50. Increasing PCTFREE causes the index to take up more space, but reduces the time required to insert or update primary key rows of the indexed table.

referential_constraint_block

FOREIGN KEY
Defines a foreign key composed of the identified columns. Consists of one or more columns in this dependent table that together must take on a value that exists in the primary key of the referenced parent table. The columns in the dependent table may contain nulls. If any of the columns contain a null value, the foreign key is considered null.

constraint_name
Provides a name for the referential constraint. A constraint_name cannot be used more than once in the same table. Although the database manager generates a constraint_name if one is not specified, a constraint_name should be explicitly chosen to make it easier for a user to drop, activate, and deactivate the foreign key.

column_name
Identifies the column or columns that comprise the foreign key. Each column_name must be an unqualified name that identifies a column of the table. The data type and length of foreign key columns must match the data type and length of the primary key columns. Only the null attribute of a foreign key column may be different. The same column cannot be specified more than once.

REFERENCES table_name
Specifies the name of the parent table involved in the referential constraint. The table_name cannot identify the table that is being altered.

ON DELETE
Defines the delete rule to be followed when a row is deleted from the parent table in a relationship.

RESTRICT
Prevents deletion of a parent row until all the dependent rows have been deleted. This is the default.

CASCADE
Causes all dependent rows to be deleted also.

SET NULL
Sets to null all columns of the foreign key values in each dependent row that can contain nulls. At least one column of the foreign key in the dependent table must be able to contain nulls.

The following restrictions for ON DELETE are checked when a table is altered.

  • If a table has more than one referential constraint referencing the same parent, all the delete rules on those constraints must be the same and must not be SET NULL.
  • If a table is delete-connected to the same parent through multiple paths, all of the delete rules on the paths, except for the last one, must be CASCADE. The last delete rule on all paths must be the same and must not be SET NULL.
  • A referential cycle involving two or more tables must not cause a table to be delete-connected to itself.

For additional information and examples of application restrictions see Definition Restrictions.

unique_block

UNIQUE
Adds a unique index automatically for the column or columns specified. If there are duplicates in the values of the columns, then a unique constraint is not added.

constraint_name
Provides a name for the unique constraint. A constraint_name cannot be used more than once in the same table. Although the database manager generates a constraint_name if one is not specified, a constraint_name should be explicitly chosen to make it easier for a user to drop, activate, and deactivate the unique constraint.

column_name
Identifies the column or columns that comprise the unique key. Each column_name must be an unqualified name that identifies a column of the table. No column in a unique constraint can be nullable. No column in a unique constraint can contain a long string. The same column cannot be specified more than once. These columns should not be the same as that of a primary key in the same table.

ASC
Creates the unique key such that the values from this column are arranged in ascending order. This is the default.

DESC
Creates the unique key such that the values from this column are arranged in descending order.

PCTFREE
Is the percentage of space in each index page reserved for later insertions and updates of unique keys. The integer may range from 0 to 99, but for practical purposes should not exceed 50. Increasing PCTFREE causes the index to take up more space, but reduces the time required to insert or update unique keys.

DROP PRIMARY KEY
Drops the definition of the primary key, thereby removing all referential constraints in which the table is a parent. Dropping a primary key causes the foreign keys that reference the parent table to be dropped.

DROP FOREIGN KEY constraint_name
Drops the definition of the foreign key, thereby removing the named referential constraint.

DROP UNIQUE constraint_name
Drops the unique index associated with the constraint and the information in the system catalog tables.

ACTIVATE ALL
Causes all the referential constraints defined for a primary key to be enforced automatically. ACTIVATE ALL is equivalent to activating the primary key, then activating all the explicitly inactive foreign keys and unique constraints.

ACTIVATE PRIMARY KEY
Causes the primary key to be enforced automatically. If the primary key is already active, this clause drops and re-creates the primary key index. If the primary key is inactive, then the primary key index is re-created first. If any dependent foreign keys are deactivated implicitly when the primary key is made inactive, those foreign keys are verified against the primary key. If the primary key index is created successfully and the dependent foreign key values are found in the primary key of the object table, then the primary key and the dependent foreign keys are activated. None of the keys are activated if an error occurs.

ACTIVATE FOREIGN KEY constraint_name
Causes the referential constraint defined by the named foreign key to be enforced automatically. If the primary key of the parent table referenced by this foreign key is inactive, the foreign key is not activated. If the associated primary key is active, the foreign key values are verified against the values in the primary key. If all values are found in the parent primary key, the dependent foreign key is activated.

ACTIVATE UNIQUE constraint_name
Activates a unique key on an existing table.

DEACTIVATE ALL
Suspends the restrictions imposed by the referential constraints and makes the parent and dependent tables involved in a referential constraint unavailable to users other than the DBA and the owner of the table. All primary and foreign keys become inactive. DEACTIVATE ALL is equivalent to deactivating the primary key, all active foreign keys in the table, and all unique constraints.

DEACTIVATE PRIMARY KEY
Suspends the restrictions imposed by the referential constraints and makes the parent and dependent tables involved in a referential constraint unavailable to users other than the DBA and the owner of the table. Deactivating a primary key drops the primary key index from the object table and implicitly deactivates all active dependent foreign keys.

DEACTIVATE FOREIGN KEY constraint_name
Suspends the restrictions imposed by the referential constraints and makes the parent and dependent tables involved in a referential constraint unavailable to users other than the DBA and the owner of the table.

DEACTIVATE UNIQUE constraint_name
Deactivates a unique key on an existing table.

DATA CAPTURE
Specifies if log records for this table should contain the full before image (DATA CAPTURE CHANGES) or the partial before image (DATA CAPTURE NONE) for UPDATE operations. If this option is not specified, it defaults to DATA CAPTURE NONE. If DataPropagator Capture is being used to capture changes to this table, DATA CAPTURE CHANGES must be specified. If DataPropagator Capture is not being used to capture updates to this table, DATA CAPTURE NONE should be specified to reduce the amount of data logged for updates to this table.

NONE
Include the partial before image in log records for UPDATE operations. If DataPropagator Capture is not being used to capture updates to this table, DATA CAPTURE NONE should be specified to reduce the amount of data logged for updates to this table.

CHANGES
Include the full before image in log records for UPDATE operations. If DataPropagator Capture is being used to capture changes to this table, DATA CAPTURE CHANGES must be specified.

Notes

It is not possible to:

It is not a good practice to:

In these cases, a warning is issued but the duplicate specification is accepted.

Adding, dropping, activating, or deactivating keys invalidates the packages that access tables affected by these changes in the keys. When an SQL statement attempts to invoke an incorrect package, the database manager tries to dynamically rebind the package.

The characteristics of a primary key or foreign key cannot be directly altered. All specifications of the key must first be dropped and then respecified.

Examples

Example 1

Add a new column named RATING, which is one character long, to the DEPARTMENT table.

  ALTER TABLE DEPARTMENT
    ADD RATING CHAR

Example 2

Add a new column named SITE_NOTES to the PROJECT table. Create SITE_NOTES as a varying-length column with a maximum length of 1000 characters. The values of the column do not have an associated character set and therefore should not be translated.

  ALTER TABLE PROJECT
    ADD SITE_NOTES  VARCHAR(1000) FOR BIT DATA

Example 3

Assume a new table EQUIPMENT has been created with the following columns:

      Column Name        Data Type
      EQUIP_NO           INT
      EQUIP_DESC         VARCHAR(50)
      LOCATION           VARCHAR(50)
      EQUIP_OWNER        CHAR(3)

Add a referential constraint to the EQUIPMENT table so that the owner (EQUIP_OWNER) must be a department number (DEPTNO) that is present in the DEPARTMENT table. If a department is removed from the DEPARTMENT table, the owner (EQUIP_OWNER) values for all equipment owned by that department should become unassigned (or set to null). Give the constraint the name DEPT_EQUIP.

  ALTER TABLE EQUIPMENT
    ADD FOREIGN KEY DEPT_EQUIP (EQUIP_OWNER)
      REFERENCES DEPARTMENT
      ON DELETE SET NULL

Example 4

Add a constraint to the PROJECT table to ensure that there are not two entries in the table with the same value for project name (PROJNAME).

  ALTER TABLE PROJECT
    ADD UNIQUE (PROJNAME)

See example 1 in CREATE INDEX for an alternate method of ensuring unique project names.

Example 5

Alter a table to create log records with the partial before image for UPDATE operations where DataPropagator Capture is not capturing updates for the table:

  ALTER TABLE SALARY1
    DATA CAPTURE NONE

Example 6

Alter a table to create log records with the full before image for UPDATE operations because DataPropagator Capture requires this information for update log records:

  ALTER TABLE SALARY2
    DATA CAPTURE CHANGES

|ASSOCIATE LOCATORS

| |

|The ASSOCIATE LOCATORS statement obtains the RESULT SET LOCATOR value for |each result set data type returned by a stored procedure.

|Invocation

|This statement can be embedded in an application program. It is an |executable statement that can be dynamically prepared. It cannot by |issued interactively.

|Authorization

|None required.

|Syntax


|

>>-ASSOCIATE----+----------------+---+-LOCATOR-------+---------->
                '-| RESULT SET |-'   |          (1)  |
                                     '-LOCATORS------'
 
         .-,----------------------.
         V                        |
>-----(-----rs-locator-variable---+---)---WITH PROCEDURE-------->
 
>-----+-host-variable--+---------------------------------------><
      '-procedure-name-'
 


Notes:


  1. RESULT SET LOCATOR variables are only supported in client applications
    written in Assembler, C, COBOL, and PL/I.


|Description |

|rs-locator-variable |
|Identifies a result set locator variable that has been declared according |to the rules for declaring result set locator variables. One result set |locator variable is required for each result set that is returned by a stored |procedure. If a stored procedure returns fewer result sets than the |number of result set locator variables specified, then the extra variables are |assigned a value of zero.

|WITH PROCEDURE host-variable or procedure-name
|Identifies the stored procedure that returns result set locators. |The procedure name may be specified either directly or within a host |variable.

|If a host-variable is specified, it must be a character-string |variable and it must not include an indicator variable. Note that the |value is not converted to uppercase.

|If procedure-name is specified, it must be an ordinary identifier, |which implies that it cannot contain blanks or special characters, and the |value is converted to uppercase. Therefore, if it is necessary to use a |lowercase name that contains blanks or special characters, then the name must |be specified in a host-variable. The procedure name must be |left-justified. The form in which a procedure name exists varies |according to the server where the procedure is stored. |

|DB2 Server for VSE & VM:
|The name of the procedure to execute. The name can be up to 18 |characters long and must match a value in the NAME column of the |SYSTEM.SYSROUTINES catalog table.

|DB2 Common Server/UDB:
|

|procedure-name
|The name (with no extension) of the procedure to execute. This is |used both as the name of the stored procedure library and the function name |within that library.

|procedure-library!function-name
|The exclamation point character acts as a delimiter between the library |name and the function name of the stored procedure.

|absolute-path!function-name
|The absolute-path specifies the complete path to the stored procedure |library. |

|In all of these cases the total length of the procedure name including its |implicit or explicit full path must not be longer than 254 bytes.

|DB2 for MVS V4 or DB2 for OS/390 V5 Server:
|An implicit or explicit three-part name. The parts are as |follows: |

|high order
|The location name of the server where the procedure is stored.

|middle
|SYSPROC

|low order
|Some value in the PROCEDURE column of the SYSIBM.SYSPROCEDURES |catalog table. |

|DB2 for OS/400 (V3.1 or later) Server:
|The external program name is assumed to be the same as the procedure |name. |

|For portability, the procedure name should be specified as a single token |no larger than eight bytes.

|The ASSOCIATE LOCATORS statement can only be executed against a stored |procedure that has already been invoked by the program using the SQL CALL |statement. |

|Notes |

  1. |More than one locator can be assigned to a result set. The same |ASSOCIATE LOCATORS statement can be issued more than once with different |result set locator variables.
  2. |If the number of result set locator variables listed in the ASSOCIATE |LOCATORS statement is less than the number of result sets returned by the |stored procedure, all variables in the statement are assigned a value, and a |warning is issued.

    |If the number of result set locator variables listed in the ASSOCIATE |LOCATORS statement is more than the number of locators returned by the stored |procedure, then the extra variables are assigned a value of zero.

  3. |The ASSOCIATE LOCATORS statement assigns result set locator values to |result set locator variables from the SQLVAR sections of the SQLDA. The |first SQLDATA field is assigned to the first locator variable, the second |SQLDATA field to the second locator variable, and so on.
  4. |For the ASSOCIATE LOCATORS statement to be successful, the application |must be connected to the site at which the stored procedure was |executed. |

|Examples

|The statements in the following examples are assumed to be in PL/I |programs.

|Example 1

|Use :loc1 and :loc2 to obtain the result set locator values |for the two result sets returned by stored procedure P1:

|   EXEC SQL ASSOCIATE RESULT SET LOCATORS (:loc1, :loc2)
|      WITH PROCEDURE P1;

|Example 2

|Use :loc1 and :loc2 to obtain the result set locator values |for the two result sets returned by the stored procedure named by host |variable :hv1:

|   EXEC SQL ASSOCIATE LOCATORS (:loc1, :loc2)
|      WITH PROCEDURE :hv1;
| |

BEGIN DECLARE SECTION

The BEGIN DECLARE SECTION statement marks the beginning of an SQL declare section where host variables must be defined.

Invocation

This statement can only be embedded in an application program. It is not an executable statement. It is not supported in REXX.

Authorization

None required.

Syntax



>>-BEGIN DECLARE SECTION---------------------------------------><
 

Description

The BEGIN DECLARE SECTION statement can be coded in the application program wherever variable declarations can appear in accordance with the rules of the host language. An SQL declare section ends with an END DECLARE SECTION statement, described on page END DECLARE SECTION.

The BEGIN DECLARE SECTION and the END DECLARE SECTION statements must be paired and may not be nested.

SQL statements (other than the 'INCLUDE text-file-name' form of the INCLUDE statement) cannot be specified within an SQL declare section.

In programs other than REXX, all variables referenced in SQL statements must be declared in one or more SQL declare sections. With the exception of Assembler, the SQL declare section must appear before the first reference to the variable. In REXX, host variables are declared without the use of these statements; meaning they are implicitly declared.

Variables declared outside an SQL declare section must not have the same name as variables declared within an SQL declare section.

Examples

Example 1

In an Assembler program, define the host variables HVSMINT (smallint), HVVCHR24 (varchar(24)), and HVDEC72 (dec(7,2)).

      EXEC SQL BEGIN DECLARE SECTION
  HVSMINT  DS    H
  HVVCHR24 DS    H,CL24
  HVDEC72  DS    PL4'12345.67'
      EXEC SQL END DECLARE SECTION

Example 2

In a C program, define the host variables hv_smint (smallint), hv_vchar24 (varchar(24)), hv_double (float), and host structure name_structure (char(9),char(9)).

  EXEC SQL  BEGIN DECLARE SECTION;
    static short                          hv_smint;
    static struct hv_char {
             short hv_vchar24_len;
             char  hv_vchar24_value[24];
           }                              hv_vchar24;
    static double                         hv_double;
    static struct name_struct {
             char  lname[9];
             char  fname[9];
           }                              name_structure;
  EXEC SQL  END DECLARE SECTION;

Example 3

In a COBOL program, define the host variables HV-SMINT (smallint), HV-VCHAR24 (varchar(24)), HV-DEC72 (dec(7,2)), and host structure NAME-STRUCTURE (char(9),char(9)).

  WORKING-STORAGE SECTION.
        EXEC SQL BEGIN DECLARE SECTION  END-EXEC.
  01  HV-SMINT              PIC S9(4)       COMP-4.
  01  HV-VCHAR24.
      49 HV-VCHAR24-LENGTH  PIC S9(4)       COMP-4.
      49 HV-VCHAR24-VALUE   PIC X(24).
  01  HV-DEC72              PIC S9(5)V9(2)  COMP-3.
  01  NAME-STRUCTURE.
      05 FNAME              PIC X(9).
      05 LNAME              PIC X(9).
        EXEC SQL END DECLARE SECTION  END-EXEC.

Example 4

In a FORTRAN program, define the host variables HVSMINT (smallint), HVCHAR24 (char(24)), and HVDOUBLE (float).

  EXEC SQL  BEGIN DECLARE SECTION
    INTEGER*2      HVSMINT
    CHARACTER*24   HVCHAR24
    REAL*8         HVDOUBLE
  EXEC SQL  END DECLARE SECTION

Note: Because varying-length character strings are not supported in FORTRAN, a character host variable large enough to use the largest expected value must be used.

Example 5

In a PL/I program, define the host variables HV_SMINT (smallint), HV_VCHAR24 (varchar(24)), HV_DEC72 (dec(7,2)), and host structure NAME_STRUCTURE (char(9),char(9)).

  EXEC SQL  BEGIN DECLARE SECTION;
    DCL  HV_SMINT     BINARY    FIXED(15);
    DCL  HV_VCHAR24   CHAR(24)  VARYING;
    DCL  HV_DEC72     FIXED     DECIMAL(7,2);
    DCL  01 NAME_STRUCTURE,
            05 FNAME     CHAR(9),
            05 LNAME     CHAR(9);
  EXEC SQL  END DECLARE SECTION;

CALL

The CALL statement invokes a stored procedure. The database manager uses the cached information from SYSTEM.SYSROUTINES, SYSTEM.SYSPARMS, and SYSTEM.SYSPSERVERS to process the statement.

Invocation

This statement must be embedded in an application program. It is an executable statement that cannot be dynamically prepared. However, a host variable can be specified for the procedure-name, enabling the procedure name to be resolved at run time.

Authorization

The privileges required to execute the CALL statement are determined by the application server and must be held by the owner of the package containing the CALL statement. If the server is DB2 Server for VSE & VM, that authorization ID must have at least one of the following for each of the packages associated with the stored procedure:

Syntax



>>-CALL----+-procedure-name-+----------------------------------->
           '-host-variable--'
 
>-----+-------------------------------------+------------------><
      +-(--+-------------------------+---)--+
      |    |  .-,------------------. |      |
      |    |  V                    | |      |
      |    '----+-host-variable-+--+-'      |
      |         +-constant------+           |
      |         '-NULL----------'           |
      '-USING DESCRIPTOR--descriptor-name---'
 

Description

procedure-name or host variable
Identifies the procedure to call. The procedure name may be specified either directly or within a host variable.

If procedure-name is specified it must be an ordinary identifier, which implies that it cannot contain blanks or special characters, and that the value is converted to upper case. If it is necessary to use lower case names, blanks, or special characters, the name must be specified in a host-variable.

If a host-variable is specified, it must be a character-string variable and it must not include an indicator variable. Note that the value is not converted to upper case. Procedure-name must be left-justified.

The procedure name can take one of several forms. The forms supported vary according to the server at which the procedure is stored.

For portability, procedure-name should be specified as a single token no larger than 8 bytes. Note that when the SQL CALL statement is preprocessed, the database manager does not check whether the procedure is defined, or whether the caller is authorized to invoke it. This checking is done at run time only.

Parameters (host variable, constant, or NULL)
Identifies a list of values to be passed as parameters to the procedure.

Each specification of a host-variable, constant, or NULL is a parameter of the CALL. If USING DESCRIPTOR is specified, each host variable described by the identified SQLDA is a parameter of the CALL. The nth parameter of the CALL corresponds to the nth parameter of the stored procedure. When the CALL statement is executed, the number of parameters of the CALL must be the same as the number of parameters expected by the stored procedure, and each pair of corresponding parameters must be consistent as explained below.

Each parameter of the stored procedure is defined at the server. In addition to attributes such as data type and length, the description of each parameter indicates how it is used by the stored procedure:

DB2 Server for VSE & VM gets the parameter descriptions from the cached information from the new catalog table SYSTEM.SYSPARMS.

Other servers might acquire parameter descriptions from other sources such as the SQL DECLARE PROCEDURE statement.

When the CALL statement is executed, the value of each parameter of the CALL defined as IN or INOUT is assigned to the corresponding parameter of the stored procedure in accordance with the DB2 Server for VSE & VM rules for assigning values to host variables. Control is then passed to the stored procedure in accordance with the calling conventions of the host language. When execution of the stored procedure is complete, the value of each parameter defined as OUT or INOUT is assigned to the corresponding parameter of the CALL in accordance with the DB2 Server for VSE & VM rules for assigning values to host variables.
Note:DB2 Server for VSE & VM does not support the use of structures or arrays for stored procedure parameters.

host-variable
The parameter of the CALL is the identified host variable. Host-variable must identify a host variable (not a structure) described in the program according to the rules for declaring host variables and the data type of the variable must be compatible with the data type of the corresponding parameter of the stored procedure. If an indicator variable is specified, its value must not be negative unless

constant
The parameter of the CALL is the specified value. The data type of the constant must be compatible with the datatype of the corresponding parameter of the stored procedure and that parameter must be defined as IN.

NULL
The parameter of the CALL is the null value. The corresponding parameter of the stored procedure must be defined as IN and the description of the stored procedure must allow for null parameters.

USING DESCRIPTOR descriptor-name
Identifies an SQLDA that must contain a valid description of host variables (unless the stored procedure has no parameters in which case the SQLDA is not used). In C, the descriptor-name can be a pointer to an SQLDA.

Before the CALL statement is processed, the user must set the following fields in the SQLDA:

Notes

  1. The capability of calling stored procedures is provided to improve the performance of distributed operations, but the capability is not limited to distributed operations. Thus, the application server can be the local DB2 Server for VSE & VM.
  2. The values of all parameters are passed from the application requester to the application server. To improve the performance of this operation, host variables that correspond to OUT parameters and have lengths of more than a few bytes should be set to null before the CALL statement is issued.
  3. If accounting is active, the activity done and resources used by the database manager on behalf of the stored procedure will be included in the accounting records of the userid that issued the SQL CALL.

Examples

Example 1

A package for a PL/I application exists on DB_A. A package for the stored procedure REPORT1 exists on DB_B. The SYSTEM.SYSROUTINES table on DB_B describes the procedure REPORT1 which allows nulls and has two parameters. The first parameter is defined as IN and the second as OUT. Here are some of the statements in the PL/I application that runs at DB_A:

   EXEC SQL CONNECT TO DB_B;
   VAR1  = 920176;
   IVAR2 = -1;
   EXEC SQL
     CALL REPORT1(:VAR1, :VAR2 INDICATOR :IVAR2);

CLOSE

The CLOSE statement closes a cursor. In doing so, it stops the usage of the group of rows pointed to by the named cursor. Closing the cursor permits the database manager to release the resources associated with maintaining an open cursor.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared.

Authorization

None required. See DECLARE CURSOR for the authorization required to use a cursor.

Syntax



>>-CLOSE--cursor_name------------------------------------------><
 

Description

cursor_name
Is an ordinary identifier that identifies the cursor to be closed. The cursor_name must identify a cursor defined in a DECLARE statement of your program.

When the CLOSE statement is processed, the cursor must be in the open state. When the CLOSE statement is processed, the indicated cursor leaves the open state, and its active set becomes undefined. No FETCH or PUT statement can be processed on the cursor, and no DELETE or UPDATE statement can refer to its current position, until the cursor is reopened by an OPEN statement.

Notes

Explicitly closing cursors as soon as possible can improve performance.

When a CLOSE statement is processed in a program that is blocking PUTS, the remaining rows in an incomplete block are inserted. SQLERRD(3) contains the number of rows that were successfully inserted.

Note that both the COMMIT and ROLLBACK statements automatically close all cursors (except when blocking an insert cursor - a COMMIT or ROLLBACK statement issued when there is an OPEN with a blocked insert cursor results in an error). CLOSE, however, does not cause a commit or rollback operation; these operations must be coded separately.

Examples

In a COBOL program, use the cursor C1 to fetch the values from the first four columns of the EMP_ACT table a row at a time and put them in the following host variables:

Finally, close the cursor.

  EXEC SQL  BEGIN DECLARE SECTION  END-EXEC.
    77 EMP              PIC X(6).
    77 PRJ              PIC X(6).
    77 ACT              PIC S9(4) COMP-4.
    77 TIM              PIC S9(3)V9(2) COMP-3.
  EXEC SQL  END DECLARE SECTION  END-EXEC.
     .
     .
     .
 
  EXEC SQL  DECLARE C1 CURSOR FOR
               SELECT EMPNO, PROJNO, ACTNO, EMPTIME
                 FROM EMP_ACT                        END-EXEC.
 
  EXEC SQL  OPEN C1  END-EXEC.
 
  EXEC SQL  FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM  END-EXEC.
 
  IF SQLSTATE = '02000'
    PERFORM DATA-NOT-FOUND
  ELSE
    PERFORM GET-REST-OF-ACTIVITY UNTIL SQLSTATE IS NOT EQUAL TO '00000'.
 
  EXEC SQL  CLOSE C1  END-EXEC.
     .
     .
     .
 
  GET-REST-OF-ACTIVITY.
  EXEC SQL  FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM  END-EXEC.
     .
     .
     .
 

Extended CLOSE

The Extended CLOSE statement "closes" the cursor_name which was opened by an Extended OPEN statement.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the statement must have one of the following:

Syntax



>>-CLOSE--cursor_variable--------------------------------------><
 

Description

cursor_variable
Identifies the cursor that is to be closed. The cursor must have been defined by a preceding Extended DECLARE CURSOR statement in the same logical unit of work.

When the cursor is closed, its active set becomes undefined. No FETCH or PUT statement can be processed on the cursor, and no DELETE or UPDATE statement can refer to its current position, until the cursor is reopened by an Extended OPEN statement.

Notes

CLOSE permits the database manager to release the resources associated with maintaining an open cursor.

In most respects, the Extended CLOSE statement is identical to the CLOSE statement (CLOSE). However, in the Extended CLOSE statement, the cursor_variable is a host variable, thereby making it possible for a user to provide the cursor_variable when the program is run and to CLOSE the cursor in a logical unit of work or program other than the one in which the statement was prepared.

Examples

CLOSE :CURSOR1

COMMENT ON

The COMMENT ON statement adds or replaces comments (also called remarks) in the catalog descriptions of tables, views, or columns.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include one of the following:

Syntax



>>-COMMENT ON--------------------------------------------------->
 
>-----+--| options_a |------------------------IS--str_constant----+>
      |                      .-,--------------------------------.     |
      |                      V                                  |     |
      '--+-table_name-+---(-----column_name--IS--str_constant---+---)-'
         '-view_name--'
 
>--------------------------------------------------------------><
 
options_a
 
|--+-TABLE--+-table_name-+--------------+-----------------------|
   |        '-view_name--'              |
   '-COLUMN--+-table_name.column_name-+-'
             '-view_name.column_name--'
 

Description

TABLE
Indicates that the comment applies to a table or view.

table_name  or  view_name
Identifies a table or view to which the comment applies. The name must identify a table or view that exists at the application server.

The comment is placed in the REMARKS column of the SYSTEM.SYSCATALOG catalog table for the row that describes the table or view.

COLUMN
Indicates that the comment applies to a column.

table_name.column_name  or  view_name.column_name
Identifies the column, qualified by the name of the table or view in which it appears. The column_name must identify a column of the specified table or view that exists at the application server.

The comment is placed into the REMARKS column of the SYSTEM.SYSCOLUMNS catalog table, for the row that describes the column.

Multiple comments
To comment on more than one column in the same table or view within the same statement, follow the table or view name with a list of one or more column names and string constant pairs in parentheses. The column_name must identify a column of the specified table or view that exists at the application server.

IS
Introduces the comment that you want to make.

string_constant
Can be any SQL character string constant of up to 254 characters. The constant may contain mixed double-byte and single-byte characters.

Examples

Example 1

Insert a comment for the EMPLOYEE table into the catalog.

  COMMENT ON TABLE EMPLOYEE
    IS 'Reflects first quarter 1981 reorganization'

Example 2

Insert a comment for the EMP_VIEW1 view into the catalog.

  COMMENT ON TABLE EMP_VIEW1
    IS 'View of the EMPLOYEE table without salary information'

Example 3

Insert a comment for the EDLEVEL column of the EMPLOYEE table into the catalog.

  COMMENT ON COLUMN EMPLOYEE.EDLEVEL
    IS 'highest grade level passed in school'

Example 4

Insert two comments into the catalog for two different columns of the EMPLOYEE table.

  COMMENT ON EMPLOYEE
  (WORKDEPT IS 'see DEPARTMENT table for names',
  EDLEVEL IS 'highest grade level passed in school ')

COMMENT ON PROCEDURE

The COMMENT ON PROCEDURE statement adds or replaces comments to the REMARKS column of the SYSTEM.SYSROUTINES catalog table for the row that describes the stored procedure identified.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The issuer must have DBA authority.

Syntax



>>-COMMENT ON PROCEDURE--procedure_name----+------------------+->
                                           '-AUTHID--authid---'
 
>----IS--string_constant---------------------------------------><
 

Description

PROCEDURE
Indicates that the comment applies to a stored procedure.

procedure_name
Identifies a stored procedure that has been defined (meaning, a CREATE PROCEDURE has been processed successfully for it).

AUTHID
Indicates that authid is specified.

authid
Identifies the authorization ID for the stored procedure. If specified, the comment will only be added or updated for the version of procedure_name that is accessible only by authid.

IS
Introduces the comment that you want to make.

string_constant
Can be any SQL character string constant of up to 254 characters. The constant may contain mixed double-byte and single-byte characters. The comment is placed into the REMARKS column of the SYSTEM.SYSROUTINES catalog table, for the row that describes the stored procedure.

Examples

Example 1

Insert a comment for the STORPRC1 stored procedure into the catalog.

  COMMENT ON PROCEDURE STORPRC1
    IS 'Calculates project cost for the current month in person-hours'

Example 2

Insert a comment for the STORPRC2 stored procedure with AUTHID USER1 into the catalog.

  COMMENT ON PROCEDURE STORPRC2 USERID USER1
    IS 'Calculates average turn-around time for service calls for the current week'

COMMIT

The COMMIT statement terminates the current logical

unit of work and commits the application server changes that were made by that logical unit of work.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that cannot be dynamically prepared.

Authorization

None required.

Syntax



           .-WORK-.
>>-COMMIT--+------+--+---------+-------------------------------><
                     '-RELEASE-'
 

Description

RELEASE

Specifies that when the COMMIT process is complete, your connection to the application server is severed.

For VM users, when the next SQL statement is entered, you are automatically connected with your logon user ID

to the default application server. This eliminates the need to enter a CONNECT statement to return to the system default user ID after being connected to an application server as another user ID.

For VSE interactive users, when the next SQL statement is entered, you are automatically connected to the CICS default user ID on the same application server. For VSE interactive users connected to a remote DRDA application server, when the next SQL statement is entered, you are automatically connected with your CICS signon user ID to the same application server.

For VSE batch applications, an explicit CONNECT with a user ID and password is necessary after a COMMIT RELEASE to establish an SQL user ID.

In any case, if you are connected to an application server with a user ID other than the default user ID and you enter a COMMIT without specifying RELEASE, you will remain connected to the application server under that user ID.

The COMMIT statement terminates the logical unit of work in which it is processed and initiates a new logical unit of work. All changes that were made by any of the following statements during the logical unit of work are committed:

  ACQUIRE DBSPACE
GRANT Package Privileges
  ALTER DBSPACE
GRANT System Authorities
  ALTER PROCEDURE
Alter a Stored Procedure
  ALTER PSERVER
Alter a Stored Procedure Server
  ALTER TABLE
GRANT Table Privileges
  COMMENT ON
INSERT
  CREATE INDEX
LABEL ON
  CREATE PACKAGE
Extended PREPARE
  CREATE PROCEDURE
Define a Stored Procedure
  CREATE PSERVER
Define a Stored Procedure Server
  CREATE SYNONYM
PUT
  CREATE TABLE
Extended PUT
  CREATE VIEW
REVOKE Package Privileges
  DELETE
REVOKE System Authorities
  DROP
REVOKE Table Privileges
  DROP PROCEDURE
Remove a Stored Procedure
  DROP PSERVER
Remove a Stored Procedure Server
  DROP STATEMENT
UPDATE
  EXPLAIN
UPDATE STATISTICS

All locks acquired by the logical unit of work are released.

All cursors that were opened during the logical unit of work are closed. All statements that were prepared during the logical unit of work using the non-extended form of the PREPARE statement are destroyed. Any cursors associated with a prepared statement that is destroyed cannot be opened until the statement is prepared again.

Notes

If a COMMIT or ROLLBACK does not immediately precede the termination of an application process, the database manager attempts to commit the work. If there are errors during the commit process, it may not be successful. It is strongly recommended that each application process explicitly ends its logical unit of work before terminating.

|The logical unit of work must be completed by using the COMMIT or |ROLLBACK statements before the CONNECT statement can be used to switch to |another user ID or application server.

|TCP/IP does not perform any security checking during a physical |connect. The Batch application requester will use the DRDA security |handshaking flows during the logical connect to perform user ID and password |verification. The physical TCP/IP connection will be deallocated and |reallocated whenever the application switches to a different user ID or server |name (using the CONNECT statement), and DRDA security handshaking flows will |be used again during the logical connect. Either of these switches will |not require the application to issue a COMMIT RELEASE or ROLLBACK |RELEASE. The Batch Resource Adapter will retain and use the current |user ID, password, and server name (unless different ones are specified with a |new CONNECT statement) after the new TCP/IP physical connection is |established. If a COMMIT RELEASE or ROLLBACK RELEASE was issued prior |to a CONNECT statement, then all user ID, password and server name information |is lost and must be supplied with the next CONNECT.

Examples

In a PL/I program, transfer a certain amount of commission (COMM) from one employee (EMPNO) to another in the EMPLOYEE table. Subtract the amount from one row and add it to the other. Use the COMMIT statement to ensure that no permanent changes are made to the database until both operations are completed successfully.

  XFRCOMM:  PROC OPTIONS(MAIN);
    EXEC SQL  BEGIN DECLARE SECTION;
      DCL  AMOUNT       FIXED DECIMAL(5,2);
      DCL  FROM_EMPNO   CHAR(6);
      DCL  TO_EMPNO     CHAR(6);
    EXEC SQL  END DECLARE SECTION;
    EXEC SQL  INCLUDE SQLCA;
    EXEC SQL  WHENEVER SQLERROR GOTO SQLERR;
    EXEC SQL  CONNECT TO TOROLAB3;
    GET LIST (AMOUNT, FROM_EMPNO, TO_EMPNO);
    EXEC SQL  UPDATE EMPLOYEE
                SET COMM = COMM - :AMOUNT
                WHERE EMPNO = :FROM_EMPNO;
    EXEC SQL  UPDATE EMPLOYEE
                SET COMM = COMM + :AMOUNT
                WHERE EMPNO = :TO_EMPNO;
    EXEC SQL  COMMIT WORK;
    RETURN;
  SQLERR:
    DISPLAY ('Unexpected Error -changes will be backed out');
    PUT SKIP LIST (SQLCA);
    EXEC SQL  WHENEVER SQLERROR CONTINUE;  /* continue if error on rollback */
    EXEC SQL  ROLLBACK WORK;
    RETURN;
  END;  /* XFRCOMM */

CONNECT (for VM)

Overall Notes

The CONNECT statement connects an application process or a user, or both, to an application server.

Invocation

This statement can only be embedded within an application program. It is an executable statement that cannot be dynamically prepared. It should be noted, however, that interactive SQL facilities, such as ISQL, provide an interface that gives the appearance of interactive execution.

Authorization

The privileges held by the authorization ID of the statement or, when specified, the authorization_name in the statement must include authorization to connect to the identified application server. If an authorization_name is specified in the statement, the appropriate password must also be specified.

Syntax



>>-CONNECT------------------------------------------------------>
 
>-----+-------------------------------------------------------------+>
      '--+-authorization_name-+---IDENTIFIED BY--+-password------+--'
         '-host_variable------'                  '-host_variable-'
 
>-----+-----------------------+--------------------------------><
      '-TO-+-server_name---+--'
           '-host_variable-'
 

Description

An application process can only be connected to one application server at a time. This is called the current server. A default application server is established when the application requester is initialized. When an application process is started, it is implicitly connected to the default application server. The application process can explicitly connect to a different application server by issuing a CONNECT statement with the TO clause. There is no default connection for CONNECT with no options. A connection lasts until one of the following occurs:

authorization_name/host_variable
Is the user ID trying to CONNECT to the application server. If used within an interactive facility, it must be a valid ordinary identifier with a maximum length of 8. If it is used in an application program, it must be a valid host variable, specified without an indicator variable, declared as a fixed-length 8-character string, and initialized before the statement is processed. (For programs written in C the host variable must be declared as a NUL-terminated string with a length of 9.) The value can be less than 8 characters; unused character positions in the host variable must be padded with blanks to the right.

IDENTIFIED BY password/host_variable
Is the password of the authorization_name. If used within an interactive facility, it must be a valid ordinary identifier with a maximum length of 8. If it is used in an application program, it must be a valid host variable, specified without an indicator variable, declared as a fixed-length 8-character string, and initialized before the statement is processed. (For programs written in C, the host variable must be declared as a NUL-terminated string with a length of 9.) The value can be less than 8 characters; unused character positions in the host variable must be padded with blanks to the right.

TO server_name/host_variable
Identifies the application server by the specified server_name or by a host_variable which contains the server_name. The server_name must be a valid ordinary identifier. Unlike authorization_name and password, if it is used in an application, it may be specified either directly or within a host variable.

If a host_variable is specified, it must be a character string variable with a length attribute that is not greater than 18, and an indicator variable may not be specified. (For programs written in C, if the host variable is declared as a NUL-terminated string, it must have a length attribute that is between 2 and 19.) The server_name that is contained within the host_variable must be left-justified and must not be delimited by quotation marks; if a fixed-length, it must be padded on the right with blanks if its length is less than that of the host variable.

The default is the currently active application server. If no application server is currently active, the default is the application server established by SQLINIT. (See the DB2 Server for VSE & VM Database Administration for information on SQLINIT.)

When the CONNECT statement is processed, the server_name must identify an application server described in the local directory (see the DB2 Server for VM System Administration manual) and the application process must be in the connectable state. (See Notes for information about connection states.)

If the CONNECT statement is successful:

If the CONNECT statement is unsuccessful because the application process is not in the connectable state or the server_name is not listed in the local directory, the connection state of the application process is unchanged. If the CONNECT statement is unsuccessful for any other reason, the application process remains in the connectable state.

CONNECT with No Operand

This form of the CONNECT statement returns information about the current authorization ID and application server. The information is returned in the SQLERRP and SQLERRMC fields of the SQLCA as described above. This form of CONNECT:

Notes

It is a good practice for the first SQL statement processed by an application process to be the CONNECT statement.

Summary of Variations of the CONNECT Statement

The various clauses may be specified in the following combinations:

  1. CONNECT

    This returns information about the currently connected authorization ID and application server.

  2. CONNECT authorization_name IDENTIFIED BY password

    This switches to a new authorization ID on the currently established application server.

  3. CONNECT TO server_name

    This switches the currently established authorization ID to a new application server.

  4. CONNECT authorization_name IDENTIFIED BY password TO server_name

    This switches to both a new authorization ID and application server.

Only variations 1 and 2 are available in single user mode.

Table 8. CONNECT Variations Supported by Communication Protocols
Variation SQLDS Protocol DRDA Protocol Single User Mode Multiple User Mode
Variation 1 Yes Yes Yes Yes
Variation 2 Yes No Yes Yes
Variation 3 Yes Yes No Yes
Variation 4 Yes No No Yes

Connection States

An application process is in one of four states at any time:

An application process is initially in the implicitly connectable state.

The connectable and connected state  An application process is connected to an application server and CONNECT statements can be processed. The process enters this state when it completes a rollback or successful commit from the unconnectable and connected state, or a CONNECT statement is successfully processed from the connectable and unconnected state.

The unconnectable and connected state  An application process is connected to an application server, but a CONNECT statement cannot be successfully processed to change application servers or to change authorization IDs. The process enters this state from the connectable and connected state when it processes any SQL statement other than CONNECT, COMMIT or ROLLBACK.

The connectable and unconnected state  An application process is not connected to an application server. The only SQL statement that can be processed is CONNECT. The process enters this state when an SQL statement is unsuccessful because of a failure that causes a rollback operation at the application server and the loss of the connection. The process can also enter this state if it processes a CONNECT statement unsuccessfully.

The implicitly connectable state  An application process is not connected to an application server and CONNECT statements can be processed. The process enters this state when it completes a rollback or successful commit with the release option from the unconnectable and connected state.

The following diagram shows the state transitions:

Figure 7. VM Connection State Transitions


View figure.

Additional Rules

It is not an error to process consecutive CONNECT statements because CONNECT itself does not remove the application process from the connectable state. It is an error to process any SQL statement other than CONNECT, COMMIT, or ROLLBACK, and then process CONNECT with any options. To avoid the error, process a commit or rollback operation before processing the CONNECT.

A CONNECT to the current application server is treated like any other CONNECT. Such a CONNECT can cause the redundant deallocation and allocation of a conversation.

Notes

A VM user ID may be transformed when using DRDA protocol. See the DB2 Server for VM System Administration manual for more information on the CMS communications directory which may cause this transformation.

The old connection will not be disconnected until the new connection is made successfully. Two connections are therefore held for a short interval. If there are many applications running concurrently that switch application servers, this may cause a wait for sessions. If experiencing delays, use COMMIT RELEASE which will disconnect explicitly.

Examples

Example 1

In a PL/I program, connect to the application server TOROLAB3.

  EXEC SQL  CONNECT TO TOROLAB3;

Example 2

In a PL/I program, switch to a different application server called TOROLAB4. Assume your user ID on TOROLAB4 is different than the one you are currently using.

  EXEC SQL  BEGIN DECLARE SECTION;
    DCL  USERID       CHAR(8);
    DCL  PASWRD       CHAR(8);
  EXEC SQL  END DECLARE SECTION;
 
 
  EXEC SQL  CONNECT :USERID IDENTIFIED BY :PASWRD
              TO TOROLAB4;

Example 3

In a PL/I program, connect to an application server whose name is stored in the host variable APP_SERVER (varchar(18)). Following a successful connection, copy the 3 character product identifier of the application server to the host variable PRODUCT (char(3)).

  EXEC SQL  CONNECT TO :APP_SERVER;
  IF SQLSTATE = '00000' THEN
  PRODUCT = SUBSTR(SQLERRP,1,3);

CONNECT (for VSE)

Overall Notes

The CONNECT statement connects an application

process or a user, or both, to an application server.

Invocation

This statement can only be embedded within an application program. It is an executable statement that cannot be dynamically prepared. It should be noted, however, that interactive SQL facilities, such as ISQL, provide an interface that gives the appearance of interactive execution.

Authorization

The privileges held by the authorization ID of the statement or, when specified, the authorization_name in the statement must include authorization to connect to the identified application server. If an authorization_name is specified in the statement, the appropriate password must also be specified.

Syntax



>>-CONNECT------------------------------------------------------>
 
>-----+------------------------------------------------------------------+>
      |                       (1)                                (1)     |
      '--+-authorization_name------+---IDENTIFIED BY--+-password------+--'
         '-host_variable-----------'                  '-host_variable-'
 
>-----+-----------------------+--------------------------------><
      '-TO-+-server_name---+--'
           '-host_variable-'
 


Notes:



  1. An implicit connect is not allowed by a Batch application
    requester. Therefore, the user ID and password must be supplied on the
    CONNECT statement used for Batch application requester processing.


Description

An application process can only be connected to one application server at a time. This is called the current server. A default application server is established when the application requester is initialized. When an application process is started and a CONNECT statement is issued, the application is connected to the default application server. The application process can explicitly connect to a different application server by issuing a CONNECT statement with the TO clause. There is no default connection for CONNECT with no options. A connection lasts until one of the following occurs:

authorization_name/host_variable
Is the user ID trying to CONNECT to the application server. If used within an interactive facility, it must be a valid ordinary identifier with a maximum length of 8. If it is used in an application program, it must be a valid host variable, specified without an indicator variable, declared as a fixed-length 8-character string, and initialized before the statement is processed. (For programs written in C the host variable must be declared as a NUL-terminated string with a length of 9.) The value can be less than 8 characters; unused character positions in the host variable must be padded with blanks to the right.

IDENTIFIED BY password/host_variable
Is the password of the authorization_name. If used within an interactive facility, it must be a valid ordinary identifier with a maximum length of 8. If it is used in an application program, it must be a valid host variable, specified without an indicator variable, declared as a fixed-length 8-character string, and initialized before the statement is processed. (For programs written in C, the host variable must be declared as a NUL-terminated string with a length of 9.) The value can be less than 8 characters; unused character positions in the host variable must be padded with blanks to the right.
Note:An implicit connect is not allowed by a Batch application requester. Therefore, the user ID and password must be supplied on the CONNECT statement used for Batch application requester processing.

TO server_name/host_variable
Identifies the application server by the specified server_name or by a host_variable which contains the server_name. The server_name must be a valid ordinary identifier. This option may be used only in an application and, unlike authorization_name and password, it may be specified either directly or within a host variable.

If a host_variable is specified, it must be a character string variable with a length attribute that is not greater than 18, and an indicator variable may not be specified. (For programs written in C, if the host variable is declared as a NUL-terminated string, it must have a length attribute that is between 2 and 19.) The server_name that is contained within the host_variable must be left-justified and must not be delimited by quotation marks; if a fixed-length, it must be padded on the right with blanks if its length is less than that of the host variable.

The default is the application server as defined in the DBNAME directory. |If a batch application attempts the connect, then the |server_name must be one that exists in the DBNAME directory. |If it is a remote server, it must be identitified as using TCP/IP |communication. Otherwise, an SQL error will be returned to the batch |application. (See the DB2 Server for VSE System Administration manual for information on the DBNAME directory.)

When the CONNECT statement is processed, the server_name must identify an application server described in the DBNAME directory (see the DB2 Server for VSE System Administration manual) and the application process must be in the connectable state. (See Notes for information about connection states.)

If the CONNECT statement is successful:

If the CONNECT statement is unsuccessful because the application process is not in the connectable state or the server_name is not listed in the DBNAME directory, the connection state of the application process is unchanged. If the CONNECT statement is unsuccessful for any other reason, the application process remains in the connectable state.

CONNECT with No Operand

This form of the CONNECT statement returns information about the current authorization ID and application server. The information is returned in the SQLERRP and SQLERRMC fields of the SQLCA as described above. This form of CONNECT:

Notes

In a batch program, either

must be the first SQL statement processed by the program. If a CONNECT TO server_name statement is processed first, it must be followed by one of the other three CONNECT statements above.

|If a CONNECT with no options is processed first, the SQLERRMT fields |will be set to a blank user ID and blank server name. In this case, |there is no default application server. If the new target server is |remote, then a new DRDA connection to that remote server will be allocated and |DRDA security handshaking will be performed. If the new target server |is local, DRDA flows are not possible and an XPCC connection will be |used. A CONNECT statement with no parameters specified returns current |connection information in the SQLERRP field of SQLCA.

|If a DRDA connection exists when a CONNECT with no options is |specified, the current connection information is returned in the SQLERRP field |of the SQLCA.

One of the remaining forms from the list above is required to establish the proper identification of the user on the application server.

If a CONNECT TO server_name is processed first, the server name is placed in the CURRENT SERVER register. Also, the SQLERRMC field in the SQLCA is set with eight blanks and the server_name separated by X'FF'. However, a CONNECT authorization_name IDENTIFIED BY password must be processed to complete the connection and establish the user identification before any other SQL statements are processed.

If the TO clause is not specified, the application is connected to the default application server. |The server_name must be one that exists in the DBNAME |directory. If it is a remote server, it must be identitified as using |TCP/IP communication. Otherwise, an SQL error will be returned to the |batch application.

|TCP/IP does not perform any security checking during a physical |connect. The Batch application requester will use the DRDA security |handshaking flows during the logical connect to perform user ID and password |verification. The physical TCP/IP connection will be deallocated and |reallocated whenever the application switches to a different user ID or server |name (using the CONNECT statement), and DRDA security handshaking flows will |be used again during the logical connect. Either of these switches will |not require the application to issue a COMMIT RELEASE or ROLLBACK |RELEASE. The Batch Resource Adapter will retain and use the current |user ID, password, and server name (unless different ones are specified with a |new CONNECT statement) after the new TCP/IP physical connection is |established. If a COMMIT RELEASE or ROLLBACK RELEASE was issued prior |to a CONNECT statement, then all user ID, password and server name information |is lost and must be supplied with the next CONNECT.

If a Logical Unit of Work is ended by a COMMIT, and a CONNECT TO server_name is the next SQL statement processed, a new connection is made to the application server specified, with the user ID and password being the same as in the previous connection.

If a Logical Unit of Work is ended with a COMMIT RELEASE, the next SQL statement must be either:

to re-establish the proper user ID.

Summary of Variations of the CONNECT Statement

The various clauses may be specified in the following combinations:

  1. CONNECT

    This returns information about the currently connected authorization ID and application server.

  2. CONNECT authorization_name IDENTIFIED BY password

    This switches to a new authorization ID on the currently established application server.

  3. CONNECT TO server_name

    This switches the currently established authorization ID to a new application server.

  4. CONNECT authorization_name IDENTIFIED BY password TO server_name

    This switches to both a new authorization ID and application server.

Connection States

An application process is in one of three states at any time:

The connectable and connected state

An application process is connected to an application server and CONNECT statements can be processed. The process enters this state when it completes a rollback or successful commit from the unconnectable and connected state, or a CONNECT statement is successfully processed from the connectable and unconnected state.

The unconnectable and connected state

An application process is connected to an application server, but a CONNECT statement cannot be successfully processed to change application servers or to change authorization IDs. The process enters this state from the connectable and connected state when it processes any SQL statement other than CONNECT, COMMIT or ROLLBACK.

The connectable and unconnected state

An application process is not connected to an application server. The only SQL statement that can be processed is CONNECT. The process is initially in this state or enters this state when an SQL statement is unsuccessful because of a failure that causes a rollback operation at the application server and the loss of the connection. The process can also enter this state if it successfully completes a commit or rollback with the release option from the unconnectable and connected state or it processes a CONNECT statement unsuccessfully.

The following diagram shows the state transitions:

Figure 8. VSE Connection State Transitions


View figure.

Additional Rules

It is not an error to process consecutive CONNECT statements because CONNECT itself does not remove the application process from the connectable state. It is an error to process any SQL statement other than CONNECT, COMMIT, or ROLLBACK, and then process CONNECT with any options. To avoid the error, process a commit or rollback operation before processing the CONNECT.

Notes

If a program is connectable and connected, a CONNECT TO server_name results in the old connection being disconnected before the new connection is attempted. If the new connection fails, the program's state is connectable and unconnected.

A CONNECT to the same application server without changing the authorization ID is treated as a no-operation; the connection is not disconnected and reconnected.

Examples

Example 1

In a PL/I program, connect to the application server TOROLAB3.

  EXEC SQL  CONNECT TO TOROLAB3;

Example 2

In a PL/I program, switch to a different application server called TOROLAB4. Assume your user ID on TOROLAB4 is different than the one you are currently using.

  EXEC SQL  BEGIN DECLARE SECTION;
    DCL  USERID       CHAR(8);
    DCL  PASWRD       CHAR(8);
  EXEC SQL  END DECLARE SECTION;
 
 
  EXEC SQL  CONNECT :USERID IDENTIFIED BY :PASWRD
              TO TOROLAB4;

Example 3

In a PL/I program, connect to an application server whose name is stored in the host variable APP_SERVER (varchar(18)).

  EXEC SQL  CONNECT TO :APP_SERVER;

Resolving Remote Server Name to Target Database

|CICS Applications

|If the CICS/VSE transaction issues an SQL CONNECT statement with the |"TO server name" clause, the server name is established explicitly for the |transaction and the Online Resource Adapter uses the DBNAME Directory to |resolve the server name to the target database.

|If the CICS/VSE transaction did not issue an SQL CONNECT statement with |the"TO server name" clause, the Online Resource Adapter attempts |to connect to the default application server, as defined in the DBNAME |Directory.

|If the target database is a Remote server and the communications protocol |to be used is SNA, the application requester issues a GDS ALLOCATE command to |acquire a session for the remote system where the server runs. The |SYSID used in this ALLOCATE command is the SYSID value from the DBNAME |Directory entry (and the SYSID must match a CEDA DEF CONNECTION |definition). Then the application requester issues a GDS CONNECT |PROCESS command to initiate an APPC basic conversation with the Remote |server. The PROCNAME used by this CONNECT PROCESS command is the REMTPN |value from the DBNAME Directory entry.

|If the target database is a Remote server and the communications protocol |to be used is TCP/IP, the application requester issues a CONNECT to the TCP/IP |listener port number that is specified by the TCPPORT value from the DBNAME |Directory entry. The target database is identified by the IPADDR or |TCPHOST values from the DBNAME Directory entry.

|If the target database is a Local or Host VM (guest sharing) server, normal |communications occurs using XPCC.

|The default application server is determined when the CIRB transaction is |invoked and can be changed subsequently by a CIRC transaction. For more |information on establishing a default application server, see DB2 Server for VSE & VM Database Administration.

|Batch Applications

|Batch applications access the Remote server in the same way as CICS |Transactions, but SNA communications protocol is not supported, only |TCP/IP. In addition, the Batch application must issue an SQL CONNECT |statement as the first SQL statement because an implicit connect is not |allowed for Batch applications.

|Communications Protocols for Remote Server Access

|The communications method used to access a Remote server by CICS |applications is specified by the Communications Protocol setting in the |SQLGLOB file, which can be either SNA or TCP/IP. The remote server to |be accessed must be connected by the desired protocol. The default |protocol in the SQLGLOB Default User entry is SNA, but this can be |changed. The protocol option can be specified for each user ID in the |SQLGLOB file. For more information about the SQLGLOB file, see DB2 Server for VSE & VM Database Administration.

|The communications method used to access a remote server by Batch |applications can only be TCP/IP; SNA is not supported for Batch |applications.

|If a server is identified in the DBNAME Directory as a Remote server, it |must contain information that identifies which communications protocols can be |used to access the Remote server. Either SNA or TCP/IP information (or |both) can be specified in the DBNAME Directory. For more information |about the DBNAME Directory, see DB2 Server for VSE & |VM Database Administration.

CREATE INDEX

The CREATE INDEX statement creates an index on a table.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

If the index name includes a qualifier that is not the same as the authorization ID of the statement, the privileges held by the authorization ID of the statement must include DBA authority.

Syntax



>>-CREATE--+--------+--INDEX--index_name-----------------------><
           '-UNIQUE-'
 
                        .-,-----------------------.
                        V               .-ASC--.  |
>>-ON--table_name--(-------column_name--+------+--+--)---------><
                                        '-DESC-'
 
   .-PCTFREE = 10------.
>>-+-------------------+---------------------------------------><
   '-PCTFREE = integer-'
 

Description

UNIQUE
Prevents the table from containing two or more rows with the same value of the index key. The constraint is enforced when rows of the table are updated or new rows are inserted.

The constraint is also checked during the execution of the CREATE INDEX statement. If the table already contains rows with duplicate key values, the index is not created.

When UNIQUE is used, null values are treated as any other values. For example, if the key is a single column that can contain null values, that column can contain no more than one null value. Unique indexes will not allow values which differ only by the number of trailing blanks.

INDEX index_name
Provides a name for the index. The name, including the implicit or explicit qualifier, must not identify an index that already exists at the application server.

If the index name is qualified, the qualifier is the owner of the index. Otherwise, the authorization ID of the statement is the owner of the index. The owner has the privilege of dropping the index.

ON table_name
Identifies the table on which you want the index to be created. The table_name must be the name of a base table (not a view) that exists at the application server. The indicated table may be empty.

(column_name,...)
Identifies a column that is to be part of the index key.

Each column_name must be an unqualified name that identifies a column of the table. Up to 16 unique columns may be specified. Indexes cannot be created for views or for columns containing long strings.

ASC
Puts the index entries in ascending order by the column. This is the default.

DESC
Puts the index entries in descending order by the column.

PCTFREE
Controls the amount of free space reserved in an index for later insertions and updates. PCTFREE defines the percentage (integer) of the total space of the index that is to be reserved for this purpose. PCTFREE may range from 0 to 99, but for practical purposes should not exceed 50. Increasing PCTFREE causes the index to take more space in the database, but reduces the time required to insert or update rows in the indexed table. If you do not include a PCTFREE clause on the CREATE INDEX statement, the database manager sets PCTFREE to 10.

Notes

If the named table already contains data, CREATE INDEX creates the index entries for it. If the table does not yet contain data, CREATE INDEX creates a description of the index; the index entries are created when data is inserted into the table.

The sum of the length attributes of the indexed columns, plus approximately 25% of the length attributes of any indexed columns of varying-length character type, must not exceed 255 bytes. If you are creating the index after data has been loaded into the table, a sort is invoked during the preprocessing of the CREATE INDEX command. If duplicate keys are allowed in the index, then the sort will require 4 bytes to be added to the encoded key. These four bytes are part of the 255 total bytes.

At preprocessing time, the database manager optimizer chooses which index, if any, is to be used in processing a given query or data manipulation statement. The index provides a fast means to access the table directly by the indexed columns. However, there is a slight increase in the time required to update the indexed columns because the database manager must also update the index. It is good practice to create indexes before preprocessing programs that might take advantage of them. When you create a new index, existing packages are not marked incorrect because they can still use their original access path. However, an existing program may run more efficiently by taking advantage of the new index. If this is the case, you should preprocess the program again. A new package is then created for the program, possibly using the new index.

An index is maintained by the database manager until it is explicitly dropped using a DROP INDEX statement, or until its table or dbspace is dropped.

Recovery of a CREATE INDEX statement could result in the index being marked as invalid. The database manager will end if an attempt is made to mark an index as not valid if the system limit of not valid indexes has been reached. The database manager will not allow a CREATE INDEX statement to proceed if the number of currently not valid indexes plus the number of potentially not valid indexes (currently executing CREATE INDEX statements plus DBSU REORGANIZE INDEX commands) has reached the limit.

If doing many updates to an indexed column or inserting many rows into an indexed table (as the Database Services utility does), it is often best to drop the index before doing the updates and then re-create it after the updates are complete. Because the index is not being updated while the table is being updated, this can be a significant performance improvement.

For information on how to calculate the length of an encoded key refer to the DB2 Server for VSE & VM Database Administration manual.

Examples

Example 1

Create an index named UNIQUE_NAM on the PROJECT table. The purpose of the index is to ensure that there are not two entries in the table with the same value for project name (PROJNAME). The index entries are to be in ascending order.

  CREATE UNIQUE INDEX UNIQUE_NAM
    ON PROJECT(PROJNAME)

See example 4 in ALTER TABLE for an alternate method of ensuring unique project names.

Example 2

Create an index named JOB_BY_DEPT on the EMPLOYEE table. Arrange the index entries in ascending order by job title (JOB) within each department (WORKDEPT). Leave 33 percent of the space in the index free for later insertions.

  CREATE INDEX JOB_BY_DEPT
    ON EMPLOYEE (WORKDEPT, JOB)
    PCTFREE = 33

CREATE PACKAGE

The CREATE PACKAGE statement creates a package.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

None required. However, a DBA authority is required to create a package that is to be owned by someone else.

Syntax



                   (1)
>>-CREATE PACKAGE----------------------------------------------->
 
>----package_spec--+------------------------------------------+-><
                   |                   .-----------------.    |
                   |                   V  (2)            |    |
                   '-USING OPTIONs--+-----------option---+-+--'
                                    '-host_variable--------'
 


Notes:



  1. PROGRAM is equivalent to PACKAGE, and is provided for compatibility with
    some older versions of the SQL/DS product.

  2. An option may be specified only once.


Description

package_spec
Provides a name for the package.

If the package_spec is identical to the name of an existing package and the REPLACE option is specified, the existing package is implicitly dropped and replaced with a new package.

USING OPTIONs option

USING OPTIONs host_variable
The options are as follows:

CCSIDSbcs (integer)
This option specifies the default CCSID to be used if a character column of subtype SBCS is defined by a CREATE or ALTER TABLE statement in this package without an explicit CCSID being specified for the column. If this option is not specified, the target application server will use its system default.

This option can only be used when connected to a DB2 Server for VM or DB2 Server for VSE application server.

CCSIDMixed (integer)
This option specifies the default CCSID to be used if a character column of subtype mixed is defined by a CREATE or ALTER TABLE statement in this package without an explicit CCSID being specified for the column. If this option is not specified, the target application server will use its system default.

This option can only be used when connected to a DB2 Server for VM or DB2 Server for VSE application server.

CCSIDGraphic (integer)
This option specifies the default CCSID to be used if a graphic column is defined by a CREATE or ALTER TABLE statement in this package without an explicit CCSID being specified for the column. If this option is not specified, the target application server will use its system default.

This option can only be used when connected to a DB2 Server for VM or DB2 Server for VSE application server.

CHARSUB Sbcs

CHARSUB Mixed

CHARSUB Bit
This option specifies the default character subtype to be used if a character column is defined by a CREATE or ALTER TABLE statement in this package without an explicit subtype or CCSID being specified. If this option is not specified, the target application server will use its system default.

This option can only be used when connected to a DB2 Server for VM or DB2 Server for VSE application server.

DATE ISO

DATE USA

DATE EUR

DATE JIS

DATE LOCAL

This option specifies which output date format will be used by the SQL statements. If the DATE option is not specified, the format specified at installation time is used. If LOCAL is implicitly or explicitly specified, a DATE installation exit must be installed.

If using DRDA protocol, ISO is the default format.

|The DATE LOCAL option is not supported for non-modifiable packages |created by using extended dynamic statements with DRDA protocol. If |specified, an error will occur indicating an incorrect parameter.

EXPLAIN NO

EXPLAIN YES
This option, if set to YES, specifies whether explanatory information for all explainable SQL statements in a package should be produced. NO is the default.

ISOLation RR

ISOLation CS

ISOLation USER

ISOLation RS

ISOLation UR

This option specifies the isolation level for the package. The DB2 Server for VSE & VM database manager supports RR, CS, UR, and USER. For a description of isolation levels, see Isolation Level. For information on USER, see the section on preprocessing and running a program in the DB2 Server for VSE & VM Application Programming manual. RR is the default.

In a VM environment, RS is not directly supported by the application server. In a VSE environment, RS is not supported at all. In both VM and VSE, isolation level RS is upgraded to level RR.

(See the IBM SQL Reference manual for details on RS.)

|The ISOLATION USER option is not supported for non-modifiable |packages created by using extended dynamic statements with DRDA |protocol. If specified, USER will be overridden with CS.

KEEP

REVOKE

This option applies if the package has previously been created and the owner of the package has granted the EXECUTE privilege on the resulting package to other users.

KEEP causes these grants of the EXECUTE privilege to remain in effect when the new package is created. KEEP is the default.

If the REVOKE option is specified, or if the owner of the package is not entitled to grant all privileges embodied in the program, the preprocessor revokes all existing grants of the EXECUTE privilege.

LABEL (label_text)
This option specifies a label for the package. Label_text can be, at most, 30 characters in length. If specified, label_text is stored in column PLABEL in the SYSTEM.SYSACCESS catalog table; the default is 30 spaces.

NOBLocK

BLocK

SBLocK

This option specifies if rows should be inserted and retrieved in groups.

If the BLocK option is specified, all eligible query cursors return results in groups of rows. All eligible insert cursors process inserts in groups of rows.

If NOBLocK is specified, rows are not grouped. This is the default.

SBLocK is primarily for use with application servers that support the FOR FETCH ONLY clause on the DECLARE CURSOR statement. The DB2 Server for VSE & VM application servers do not support this clause, but the DB2 Server for VM application requester can connect to application servers that do support FOR FETCH ONLY.

NOCHECK

CHECK

|ERROR
This option specifies what action to take when an SQL statement is prepared into the package and checked for validity. For all options, if a statement fails its validity check, an appropriate SQLCODE and SQLSTATE is returned in the SQLCA.
  • If NOCHECK is specified and any SQL statement fails its validity check, the package will not be created. This is the default.
  • If CHECK is specified, the package is not created, even if all SQL statements pass their validity check.
  • |If ERROR is specified, the package is created even if any SQL |statement fails its validity check. The subsequent execution of a not |valid statement results in a -525 SQLCODE, SQLSTATE 51015. Note that |for a modifiable package, ERROR and EXIST may not be specified |together.

NODESCRIBE

DESCRIBE

This option allows the use of the Extended DESCRIBE for statements added to the created package.

If DESCRIBE is specified, Extended DESCRIBE statements can be processed.

If NODESCRIBE is specified, these Extended DESCRIBE statements cannot be processed. This is the default. NODESCRIBE is not supported with DRDA protocol and will be changed to DESCRIBE.

NOEXIST

EXIST

This option specifies the action to be taken when objects referenced in a program are checked for existence and their access authorizations are checked.

If NOEXIST is specified, a warning is returned to the program if object and authorization existence is not found. This will not affect the creation of the package (for instance, if NOCHECK is in effect and everything else is valid, then the package will be created). NOEXIST is the default.

If EXIST is specified, an error is returned to the program if an object does not exist or if the authorization ID of an Extended PREPARE statement does not have the appropriate privileges on an object. In such a case, the package is not created, even if ERROR is specified. For modifiable packages, ERROR and EXIST may not be specified together.

NOMODIFY

MODIFY

This option specifies whether the created package can be modified after it is stored through a COMMIT. Sections are added to the package by using the Extended PREPARE and deleted by using the DROP STATEMENT function.

Sections in packages created with the MODIFY option can also be processed or dropped before committing the logical unit of work in which they were prepared.

The MODIFY option should not be used if the entire package will be replaced using the REPLACE option. Once a package has been created with the MODIFY option specified, it can be changed but not replaced by subsequent CREATE PACKAGE statements. To replace a package created with the MODIFY option, it is necessary to enter a DROP PACKAGE statement and then enter a CREATE PACKAGE.

NOMODIFY is supported with DRDA protocol; however, there are some restrictions (see Appendix G, DRDA Considerations). MODIFY is not supported with DRDA protocol and will be changed to NOMODIFY. NOMODIFY is the default.

OWner (authorization_name)
This option specifies the owner of the package being created. If this option is not specified, the binder's authorization ID at the application server is used.

For DB2 Server for VSE & VM application servers, the authorization_name must be the same as the binder's authorization ID at the application server.

QUALifier (collection_id)
This option specifies the default collection_id to be used within the package to resolve unqualified object names. If this option is not specified, the binder's authorization ID at the application server is used.

For DB2 Server for VSE & VM application servers, the collection-id must be the same as the binder's authorization ID at the application server.

RELease COMMIT

RELease DEALLOCATE
This option specifies when the application server should release the package execution resources and any associated locks.

If COMMIT is specified, the resources are released when a logical unit of work (LUW) is committed or rolled back. This is the default.

If DEALLOCATE is specified, the resources are released when the application process terminates.

For DB2 Server for VSE & VM application servers, the only acceptable option is RELEASE(COMMIT).

REPLACE

NEW

This option specifies whether the package being created is new or whether it will replace an existing package that has the same name. REPLACE is the default.

If NEW is specified, an error results if a package already exists with the same name.

If REPLACE is specified and no previous package exists with the same name, no error or warning is given. If NEW is specified along with KEEP or REVOKE, an error results.

TIME ISO

TIME USA

TIME EUR

TIME JIS

TIME LOCAL
This option specifies which output time format will be used by the SQL statements. If the TIME option is not specified, the format specified at installation time is used. If LOCAL is implicitly or explicitly specified, a TIME installation exit must be installed.

If using DRDA protocol, ISO is the default format.

|The TIME LOCAL option is not supported for non-modifiable packages |created by using extended dynamic statements with DRDA protocol. If |specified, an error will occur indicating an incorrect parameter.

host_variable
Contains a list of options, delimited by a comma or blank. This host variable must be declared as VARCHAR and has a maximum length of 8192.

Notes

The package is stored in the database when a COMMIT is issued.

When the logical unit of work, in which the CREATE PACKAGE statement is entered, is committed (using COMMIT), a new package is created. ROLLBACK prevents the storage of the new package. A package created with the MODIFY option can be committed even if it contains no statements. Only one package may be created or modified within a logical unit of work.

Before SQL/DS Version 3 Release 1, the values for the ISOLATION, DATE, and TIME bind options were derived from the corresponding options with which the application was preprocessed. With SQL/DS Version 3 Release 1, these options became pure bind options, meaning that their values are to be based only on their specification in the CREATE PACKAGE statement. This change will only take effect after the application issuing the CREATE PACKAGE statement has been repreprocessed, reassembled, and relinked.
Note:For DB2 Server for VSE, if a combination of the NOBIND, BIND, or the PACKAGE, NOPACKAGE or the CHECK, NOCHECK and ERROR was specified, the preprocessor will generate an error message. For example, if PACKAGE, NOPACKAGE, NOBIND, BIND were all specified, the preprocessor will display the following error messages:
     ARI0583E - Keywords PACKAGE and NOPACKAGE were both found.
              - Specify only one.
     ARI0583E - Keywords NOBIND and BIND were both found.
              - Specify only one.
     ARI0586I - Preprocessing ended with 2 errors and
              - 0 warnings.

For DB2 Server for VSE, if NOBIND, NOCHECK and NOPACKAGE are all specified, no action would be taken for this preprocessing. This is considered an error and the following error messages will be displayed:

     ARI5411E - Keywords NOBIND, NOCHECK and NOPACKAGE are
              - specified. No preprocess will be done for this
              - operation.
     ARI0586I - Preprocessing ended with 1 errors and
              - 0 warnings.

|The restriction for non-modifiable packages created by using |extended dynamic statements with DRDA protocol are as follows: |

Examples

CREATE PACKAGE JERRY.MUSICIANS USING OPTIONS DESCRIBE NEW BLOCK

CREATE PROCEDURE

The CREATE PROCEDURE statement inserts the definition of a stored procedure and the parameters it requires into SYSTEM.SYSROUTINES and SYSTEM.SYSPARMS, and into the cache.

Invocation

This statement can be issued from an application program or interactively. It is an executable statement that can be dynamically prepared.

Authorization

The issuer of the CREATE PROCEDURE must have DBA authority.

Syntax

>>-CREATE PROCEDURE---procedure-name----+-----------------+--(-->
                                        '-AUTHID--authid--'
 
>-----+----------------+--)------------------------------------->
      '-| parameters |-'
 
      .-,------------------------------------------------------.
      |              (1)                                       |
      V     .-FENCED------------------------------------.      |  (8)
>---------+-+-------------------------------------------+-+----+----->
          | +-LANGUAGE-+-ASSEMBLE-+---------------------+ |
          | |          +-C--------+                     | |
          | |          +-COBOL----+                     | |
          | |          '-PLI------'                     | |
          | +-EXTERNAL-+------------------------------+-+ |
          | |          '-NAME--external-program-name--' | |
          | +-SERVER GROUP--+-------------------+-------+ |
          | |               '-server-group-name-'       | |
          | | .-DEFAULT SERVER GROUP YES--.             | |
          | +-+---------------------------+-------------+ |
          | | '-DEFAULT SERVER GROUP NO---'             | |
          | '-+------------------------------+----------' |
          |   +-PARAMETER STYLE--------------+            |
          |   |                      (3)     |            |
          |   | .-GENERAL WITH NULLS-------. |            |
          |   |-|         (2)              | |            |
          |   '-+-GENERAL------------------+-'            |
          | .-STAY RESIDENT NO--.                         |
          +-+-------------------+-------------------------+
          | '-STAY RESIDENT YES-'                         |
          | .-PROGRAM TYPE MAIN-----.                     |
          +-+-----------------------+---------------------+
          | |                  (4)  |                     |
          | '-PROGRAM TYPE SUB------'                     |
          +-+--------------------------------+------------+
          | '-RUN OPTIONS--run-time-options--'            |
          | .-RESULT SET 0-------------.                  |
          +-+--------------------------+------------------+
          | '-RESULT-+-SET--+--integer-'                  |
          |          '-SETS-'                             |
          | .-COMMIT ON RETURN NO--.                      |
          +-+----------------------+----------------------+
          | '-COMMIT ON RETURN YES-'                      |
          |                     (5)                       |
          | .-NOT DETERMINISTIC-------.                   |
          +-+-------------------------+-------------------+
          | |               (6)       |                   |
          | '-DETERMINISTIC-----------'                   |
          |                (7)                            |
          | .-CONTAINS SQL-----------.                    |
          +-+------------------------+--------------------+
          | |        (7)             |                    |
          | +-NO SQL-----------------+                    |
          | |                (7)     |                    |
          | +-READS SQL DATA---------+                    |
          | |                   (7)  |                    |
          | '-MODIFIES SQL DATA------'                    |
          |             (7)                               |
          | .-NO COLLID-------------------.               |
          +-+-----------------------------+---------------+
          | |                       (7)   |               |
          | '-COLLID--collection-id-------'               |
          +-+-----------------------------------+---------+
          | |                 (7)               |         |
          | +-WLM ENVIRONMENT------+-name-----+-+         |
          | |                      '-(name,*)-' |         |
          | |                    (7)            |         |
          | '-NO WLM ENVIRONMENT----------------'         |
          |                    (7)                        |
          | .-ASUTIME NO LIMIT-------------.              |
          +-+------------------------------+--------------+
          | |                        (7)   |              |
          | '-ASUTIME LIMIT--integer-------'              |
          |                         (7)                   |
          | .-EXTERNAL SECURITY DB2--------------.        |
          +-+------------------------------------+--------+
          | |                   (7)              |        |
          | '-EXTERNAL SECURITY------+-USER----+-'        |
          |                          '-DEFINER-'          |
          |             (7)                               |
          | .-NO DBINFO-------.                           |
          '-+-----------------+---------------------------'
            |        (7)      |
            '-DBINFO----------'
 
>--------------------------------------------------------------><
 

Notes:

  1. This parameter is included for compatibility with the DB2 family. If specified, it is ignored.

  2. As an alternative to GENERAL, SIMPLE CALL may be used. This is for compatibility within the DB2 family.

  3. As an alternative to GENERAL WITH NULLS, SIMPLE CALL WITH NULLS may be used. This is for compatibility within the DB2 family.

  4. Currently, DB2 Server for VSE & VM supports stored procedures written as main programs only.

  5. VARIANT may be specified as an alternative to NOT DETERMINISTIC. This is for compatibility within the DB2 family.

  6. NOT VARIANT may be specified as an alternative to DETERMINISTIC. This is for compatibility within the DB2 family.

  7. This parameter is included for compatibility with the DB2 family. If specified, it is ignored.

  8. One or more clauses may be specified, however each clause may be specified at most once.

Description

Only the parameters that are meaningful to DB2 Server for VSE & VM are described.

procedure-name
Names the stored procedure. For DB2 Server for VSE & VM, the name must be an ordinary identifier of 18 characters or less. The name must not identify a stored procedure that already exists on the server. In addition, the name cannot be 'AUTHID' or 'ACTION'.

authid
The authorization ID for the stored procedure. authid must be an ordinary identifier of 8 characters or less. If specified, then the stored procedure being defined will be accessible only by by authid. Note that authid cannot be 'AUTHID' or 'ACTION'.

LANGUAGE
Specifies the programming language used to create the stored procedure. All stored procedure programs must be designed to run in the IBM Language Environment.

ASSEMBLE
Specifies that the stored procedure is written in Assembler.

C
Specifies that the stored procedure is written in C.

COBOL
Specifies that the stored procedure is written in COBOL.

PLI
Specifies that the stored procedure is written in PLI.

Note that the LANGUAGE clause must be specified on the CREATE PROCEDURE statement.

EXTERNAL NAME external-program-name
Identifies the load module or phase associated with the stored procedure. The load module or phase does not need to exist when the CREATE PROCEDURE statement is issued. However, when a CALL for the stored procedure is issued, the load module must exist and be accessible to the stored procedure server.

If external-program-name is not specified, the name of the load module or phase is assumed to be the same as the name of the stored procedure. In this case, the name of the stored procedure must be 8 characters or less. Note that the EXTERNAL clause must be specified on the CREATE PROCEDURE statement.

SERVER GROUP server-group-name
Identifies the name of the group of servers to be used to run this stored procedure. Server-group-name must be an ordinary identifier of 18 characters or less, and must be defined in SYSTEM.SYSPSERVERS.

If SERVER GROUP is specified without server-group-name, the stored procedure must be able to run in the default server group. Note that the SERVER GROUP clause must be specified on the CREATE PROCEDURE statement.

DEFAULT SERVER GROUP
Specifies whether the stored procedure can run in the default server group.

YES
The stored procedure can run in the default server group. This is the default.

NO
The stored procedure cannot run in the default server group. If NO is specified, a server-group-name must be provided on the SERVER GROUP clause.

PARAMETER STYLE
Identifies the linkage convention used to pass parameters to the stored procedure. All of the linkage conventions provide arguments to the stored procedure containing the parameters specified on the SQL CALL statement. See the DB2 Server for VSE & VM Database Administration manual for more information. The following parameter styles options are valid for DB2 Server for VSE & VM:

GENERAL
If the GENERAL linkage convention is used:
  • the SQL CALL statement must provide a parameter for each parameter expected by the stored procedure
  • input parameters cannot be null
  • nulls can be passed for output parameters only
  • the stored procedure cannot return nulls for output parameters

Note that DB2 Server for VSE & VM does not support the parameter style DB2SQL.

GENERAL WITH NULLS
If the GENERAL WITH NULLS linkage convention is used:
  • the SQL CALL statement must provide a parameter for each parameter expected by the stored procedure. When the database manager invokes the stored procedure, it sends it the parameters specified on the SQL CALL statement, as well as an array of indicator variables (with one indicator variable for each parameter). The stored procedure must contain a declaration for this array.
  • input parameters can be null. This is achieved through the use of indicator variables, or by specifying the keyword null.
  • the stored procedure can return nulls for output parameters, by using indicator variables.

STAY RESIDENT
Specifies whether the stored procedure load module or phase remains loaded in memory after the stored procedure ends. Possible values are:

NO
The load module or phase is deleted from memory after the stored procedure ends. This is the default.

YES
The load module or phase remains loaded in memory after the stored procedure ends.

PROGRAM TYPE
Specifies whether the stored procedure runs as a MAIN routine or as a SUB routine. Currently, DB2 Server for VSE & VM supports stored procedures written as MAIN routines only.

RUN OPTIONS
Specifies the Language Environment run-time options to be passed to the stored procedure. The options must be specified as a character string up to 254 bytes and must be enclosed in single quotation marks. If this option is not specified, or an empty string is passed, then DB2 Server for VSE & VM passes no run-time options to the Language Environment, and Language Environment uses its installation defaults. Note that DB2 Server for VSE & VM does not do any checking of the options provided. For a complete description of Language Environment run-time options, see Language Environment for MVS & VM Programming Reference.

RESULT SETS or RESULT SET
Specifies the maximum number of query result sets that can be returned by this stored procedure. The default is RESULT SETS 0, indicating that there are no result sets. The largest value that can be specified is 32767.

COMMIT ON RETURN
Indicates whether the transaction should be committed immediately upon return from the stored procedure.

NO
The database manager should not issue COMMIT when the stored procedure returns. This is the default.

YES
The database manager should issue COMMIT when the stored procedure returns when the following statements are true:
  • The SQLCODE returned by the CALL statement is not negative
  • The stored procedure is not in a must abort state

The COMMIT operation includes the work performed by the calling application as well as the stored procedure. Any cursors that are open when the COMMIT occurs will be closed during COMMIT processing.

Parameters



 
parameters
 
   .-,-------------------------------------------------------------------.
   V  .-IN----.                                                          |
|-----+-------+---+----------------+--| data-type |-+-----------------+--+->
      +-OUT---+   '-parameter-name-'                |            (1)  |
      '-INOUT-'                                     '-AS LOCATOR------'
 
>---------------------------------------------------------------|
 
data-type
 
|---+-INT---------------------------------------------------------+->
    +-INTEGER-----------------------------------------------------+
    +-SMALLINT----------------------------------------------------+
    +-REAL--------------------------------------------------------+
    +-FLOAT-------------------------------------------------------+
    +-DOUBLE------------------------------------------------------+
    +-DOUBLE PRECISION--------------------------------------------+
    +--+-DECIMAL-+---+-------------------------------+------------+
    |  '-DEC-----'   '-(--integer--+----------+---)--'            |
    |                              '-,integer-'                   |
    +--+-CHARACTER-+---+-----------+---+------------------------+-+
    |  '-CHAR------'   '-(integer)-'   '-FOR--+-SBCS--+---DATA--' |
    |                                         +-MIXED-+           |
    |                                         '-BIT---'           |
    +-VARCHAR(integer)---+------------------------+---------------+
    |                    '-FOR--+-SBCS--+---DATA--'               |
    |                           +-MIXED-+                         |
    |                           '-BIT---'                         |
    +-GRAPHIC(integer)--------------------------------------------+
    '-VARGRAPHIC(integer)-----------------------------------------'
 
>---------------------------------------------------------------|
 


Notes:



  1. This parameter is included for compatibility with the DB2 family.
    If specified, it is ignored.


The fields of the parameters syntax diagram are:

IN
The parameter is an input-only parameter to the stored procedure.

OUT
The parameter is an output-only parameter to the stored procedure.

INOUT
The parameter is both an input and output parameter to the stored procedure.

parameter-name
a one- to eight-character ordinary identifier defining the name of the parameter for use in messages. If you do not specify a name, the position of the parameter in the parameter list is used in the DB2 Server for VSE & VM messages.

INTEGER or INT
Large integer parameter

SMALLINT
Small integer parameter

REAL
Single precision floating point

FLOAT, DOUBLE, or DOUBLE PRECISION
Double precision floating point

DECIMAL or DEC
Decimal parameter. The (integer,integer) optional arguments are the precision and scale respectively. The precision is the total number of digits from 1 to 31. The scale is the number of digits to the right of the decimal point, from 0 to the precision.

CHARACTER or CHAR
Fixed length character string parameter. The (integer) optional argument specifies the length of the string, from 1 to 254. If you do not specify (integer), the length is set to 1.

VARCHAR
Varying length character string parameter. The maximum length is specified by the argument (integer) and varies from 1 to 32767. If the length is greater than 254 then it is a long string column.

GRAPHIC
Fixed-length graphic string parameter. The (integer) optional argument specifies the length of the string, from 1 to 127. If you do not specify the (integer) argument, the length is set to 1.

VARGRAPHIC
Varying-length graphic character string parameter. The maximum length is specified by the argument (integer) and varies from 1 to 16383 characters.

FOR subtype DATA
Specifies a subtype for a character string parameter. The subtype can be one of the following:

SBCS
Specifies that the parameter is a single-byte character string.

MIXED
Specifies that the parameter holds mixed single-byte and double-byte data. This option is valid only when the DBCS value is set to YES.

BIT
Specifies that the parameter holds bit data. Character conversion does not occur for data that is defined FOR BIT DATA

As an example, in the following parameters string:

PARM1 CHAR(10) IN, PARM2 INTEGER INOUT, PARM3 INT OUT

PARM1, PARM2, and PARM3 are identifiers for error messages. You can specify any name you want. The stored procedure associated with the PARMLIST string would expect three parameters:

Notes

  1. If a parameter represents a DB2 Server for VSE & VM DATE, TIME, or TIMESTAMP value, it must be defined as CHARACTER or VARCHAR in the PARMLIST.
  2. Refer to the appendices of the DB2 Server for VSE & VM Application Programming manual for the programming language declarations that correspond to the datatypes in the PARMLIST.

Examples

Example 1

   CREATE PROCEDURE MYPROC (IN INT, IN PARM2 CHAR(10), OUT CHAR(20))
      EXTERNAL NAME MYMOD,
      LANGUAGE COBOL,
      PARAMETER STYLE GENERAL
 
   CREATE PROCEDURE MYPROC2 (IN INT, IN CHAR(10), OUT CHAR(20))
      EXTERNAL NAME MYMOD2,
      LANGUAGE COBOL,
      PARAMETER STYLE GENERAL WITH NULLS,
      RUN OPTIONS 'HEAP(,,ANY),BELOW(4K,,),ALL31(ON),STACK,(,,ANY,)'
 

CREATE PSERVER

The CREATE PSERVER statement inserts the definition of a stored procedure server into SYSTEM.SYSPSERVERS and puts the new definition into the cache.

Invocation

This statement can be issued from an application program or interactively. It is an executable statement that can be dynamically prepared.

Authorization

The issuer of the CREATE PSERVER statement must have DBA authority.

Syntax



                                     .-,-------------------------------.
                                     V                                 |
>>-CREATE PSERVER--procedure-server-----+---------------------------+--+->
                                        |  (1)                      |
                                        +---------------------------+
                                        +-GROUP--group-name---------+
                                        | .-AUTOSTART NO--.         |
                                        +-+---------------+---------+
                                        | '-AUTOSTART YES-'         |
                                        '-DESCRIPTION--description--'
 
>--------------------------------------------------------------><
 


Notes:


  1. One or more clauses may be specified, however each clause may be specified
    at most once.


Description

procedure-server
The name of the stored procedure server. The name must be an ordinary identifier of 8 characters or less. The name must not identify a stored procedure server that already exists on the server. In addition, the name cannot be one of the following:
GROUP
IMPLICIT
NOIMPLICIT
NORMAL
QUICK

GROUP
The name of the group that this stored procedure server is in. Using stored procedure groups gives the database administrator more flexibility in defining the system. The use of stored procedure groups is optional; if the GROUP clause is not specified, the stored procedure server becomes part of the default group. If the GROUP clause is specified, the group-name must be an ordinary identifier of 1 to 18 characters.

AUTOSTART
Determines whether the database manager will issue a START PSERVER command for this stored procedure server when the database is started.

NO
The stored procedure server will not be started when the database is intialized. This is the default.

YES
The stored procedure server will be started when the database is initialized.

DESCRIPTION
This field provides the database administrator with a place to provide information about this stored procedure server, such as virtual storage requirements, other servers in the group, and so on. Description can be up to 254 characters and must be enclosed in single quotation marks. The default is NULL.

Examples

Example 1

   CREATE PSERVER SRV1 GROUP GRP1, AUTOSTART YES
   CREATE PSERVER SRV2 GROUP GRP2, AUTOSTART YES

CREATE SYNONYM

The CREATE SYNONYM statement defines an alternative name for a table or view. This lets you refer to a table or view owned by another user without having to enter the qualified name. You may also define a synonym for a table or view that you own.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

None required.

Syntax



>>-CREATE SYNONYM--synonym--FOR----+-qualified_table_name-+----><
                                   '-qualified_view_name--'
 

Description

synonym
Provides an alternative name to use when referring to the table or view. The synonym must be an SQL identifier that is not identical to one of your synonyms or the unqualified name of a table or view that you own.

FOR
Identifies the qualified name of the table or view for which the synonym is to be created. The qualifier is required, even when you are creating a synonym for one of your own tables or views. You can create a synonym for a table or view that does not as yet exist in the system catalog.

The synonym is defined only for your authorization ID, that is, the authorization ID of the statement. If many users want to have the same synonym, each user must enter a CREATE SYNONYM statement.

qualified_table_name

qualified_view_name
Identifies the object to which the synonym will apply. The name consists of two parts and denotes a table or view already described or which will be described in the catalog.

Notes

A synonym cannot be used with the table or view it represents in the same statement.

Examples

Define an alternative name, PARTS, for TRUDEAU.INVENTORY.

  CREATE SYNONYM PARTS
    FOR TRUDEAU.INVENTORY

CREATE TABLE

The CREATE TABLE statement defines a table. You provide the name of the table and the names and attributes of its columns. Moreover, you may specify the dbspace where the table is to be created.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

If the table name is qualified by an identifier other than your authorization ID, you must have DBA authority.

See the description of the IN clause for further information on authorization.

Syntax



>>-CREATE TABLE--table_name--(---------------------------------->
 
      .-,---------------------------------------------.
      V   (1)                                         |
>---------------+-| column_definition_block |------+--+--)------>
                |                       (1)        |
                +-| primary_key_block |------------+
                +-| referential_constraint_block |-+
                '-| unique_block |-----------------'
 
      .----------------------------------------.
      V                                        |
>--------+----------------------------------+--+---------------><
         +-IN--dbspace_name-----------------+
         |  (3)                             |
         '--------DATA CAPTURE--+-NONE----+-'
                                '-CHANGES-'
 


Notes:



  1. There can be up to 255 columns in a table.

  2. Only one primary key may be defined (either in a
    primary_key_block or as a column attribute).

  3. The same clause must not be specified more than once.


 
column_definition_block
 
|--column_name-------------------------------------------------->
 
>-----| data_type |--+-----------------------------+------------|
                     |  (1)                        |
                     '--------| fieldproc_block |--'
 


Notes:



  1. These clauses may be specified in any order.

  2. Only one primary key may be defined (either in a
    primary_key_block or as a column attribute).


 
data_type
 
|--+-INTeger--------------------------------------------------+->
   +-SMALLINT-------------------------------------------------+
   |          .-(53)------.                                   |
   +-+-FLOAT--+-----------+-+---------------------------------+
   | |        '-(integer)-' |                                 |
   | +-REAL-----------------+                                 |
   | '-DOUBLE PRECISION-----'                                 |
   |                .-(5,0)------------------------.          |
   +--+-DECimal-+---+------------------------------+----------+
   |  '-NUMERIC-'   '-(--integer--+----------+--)--'          |
   |                              '-,integer-'                |
   |               .-(1)-------.                              |
   +--+-CHARacter--+-----------+-+---+-----------------+------+
   |  |            '-(integer)-' |   |  (1)            |      |
   |  +-VARCHAR--(integer)-------+   +-----------------+      |
   |  '-LONG VARCHAR-------------'   +-FOR SBCS DATA---+      |
   |                                 +-FOR MIXED DATA--+      |
   |                                 +-FOR BIT DATA----+      |
   |                                 '-CCSID--integer--'      |
   |             .-(1)-------.                                |
   +--+-GRAPHIC--+-----------+-+---+------------------------+-+
   |  |          '-(integer)-' |   |  (1)                   | |
   |  +-VARGRAPHIC--(integer)--+   '--------CCSID--integer--' |
   |  '-LONG VARGRAPHIC--------'                              |
   |                                                          |
   +-DATE-----------------------------------------------------+
   +-TIME-----------------------------------------------------+
   '-TIMESTAMP------------------------------------------------'
 
>-----+----------------------------------------+----------------|
      |  (1)                                   |
      '--------NOT NULL--+------------------+--'
                         +-UNIQUE-----------+
                         |             (1)  |
                         '-PRIMARY KEY------'
 



 
fieldproc_block
 
|--FIELDPROC--program_name----+-------------------------+-------|
                              |    .-,-----------.      |
                              |    V             |      |
                              '-(-----constant---+---)--'
 
 
primary-key-block
 
                     .-,------------------------------.
                     V   (1)                .-ASC--.  |
|--PRIMARY KEY--(--------------column_name--+------+--+--)------>
                                            '-DESC-'
 
      .-PCTFREE = 10------.
>-----+-------------------+-------------------------------------|
      '-PCTFREE = integer-'
 


Notes:



  1. A PRIMARY KEY can have up to 16 columns.


 
referential-constraint-block
 
                                          .-,--------------.
                                          V                |
|--FOREIGN KEY--+-----------------+--(-------column_name---+---->
                '-constraint_name-'
 
>----)--REFERENCES--table_name----+---------------------------+-|
                                  |            .-RESTRICT--.  |
                                  '-ON DELETE--+-CASCADE---+--'
                                               '-SET NULL--'
 
 
unique-block
 
|--UNIQUE--+-----------------+---------------------------------->
           '-constraint_name-'
 
        .-,------------------------------.
        V   (1)                .-ASC--.  |
>----(------------column_name--+------+--+---)------------------>
                               '-DESC-'
 
      .-PCTFREE = 10------.
>-----+-------------------+-------------------------------------|
      '-PCTFREE = integer-'
 


Notes:



  1. There can be up to 16 columns on a unique constraint.


Description

table_name
Provides a name for the table. The name, including the implicit or explicit qualifier, must not identify a table, view, or synonym that already exists at the application server.

If the table name is qualified, the qualifier is the owner of the table. Otherwise, the authorization ID of the statement is the owner of the table. The owner has all privileges on the table. The privileges can be granted by the owner and cannot be revoked from the owner.

If user SCOTT preprocesses a program that creates a table named SUMMARY, and user JONES runs the program, the owner of the SUMMARY table is SCOTT. Note that JONES must be a DBA to run the program. Any program preprocessed by SCOTT can refer to the SUMMARY table simply by the name SUMMARY. When another authorization ID preprocesses a program that refers to the SUMMARY table, the program must use SCOTT as a prefix to the table_name, SCOTT.SUMMARY.

(column_name,...)
Names a column of the table. Do not qualify column_name and do not use the same name for more than one column of the table.

data_type
Specifies one of the types in the following list.

INTeger

For a large integer. The value may range from -2147483648 to 2147483647.

SMALLINT
For a small integer. The value may range from -32 768 to 32 767.

FLOAT(integer)

FLOAT
For a floating-point number. If the integer is between 1 and 21 inclusive, the format is that of single precision floating-point. If the integer is between 22 and 53 inclusive, the format is that of double precision floating-point. If the integer is omitted from the specification, double precision floating-point is assumed.

In place of FLOAT(integer) you may specify either:

REAL
For single precision floating-point
DOUBLE PRECISION
For double precision floating-point

DECIMAL(precision-integer,scale-integer)

For a packed decimal number. The first integer is the precision of the number; that is, the total number of digits; it can range from 1 to 31. The second integer is the scale of the number; that is, the number of digits to the right of the decimal point; the scale of the number can range from 0 to the precision of the number.

DECIMAL(p) can be used for DECIMAL(p,0), and DECIMAL can be used for DECIMAL(5,0).

NUMERIC
NUMERIC is a synonym for DECIMAL.

CHARacter(integer)

CHARacter
For a fixed-length character string of length integer, which can range from 1 to 254 bytes. If the length specification is omitted, a length of 1 character is assumed.

VARCHAR(integer)
For a varying-length character string of maximum length integer, which can range from 1 to 32 767 bytes. An integer greater than 254 defines a long string column.

LONG VARCHAR
For a varying-length character string with a maximum length of 32 767 bytes.

A LONG VARCHAR column is always a long string column (even if its actual length is 254 or less).

GRAPHIC(integer)
For a fixed-length graphic string of length integer, which can range from 1 to 127 double-byte characters. If the length specification is omitted, a length of 1 character is assumed.

VARGRAPHIC(integer)
For a varying-length graphic string of maximum length integer, which must range from 1 to 16 383 double-byte characters. An integer greater than 127 double-byte characters defines a long string column.

LONG VARGRAPHIC
For a varying-length string of double-byte characters, of maximum length 16 383 bytes. A LONG VARGRAPHIC column is always a long string column (even if its actual length is 127 double-byte characters or less).

DATE
For a date.

TIME
For a time.

TIMESTAMP
For a timestamp.

column clauses  (can be specified in any order) 

NOT NULL
Prevents the column from containing null values.

NOT NULL PRIMARY KEY
Establishes a primary key column. (See "PRIMARY KEY" in the primary-key-block section for a definition of a primary key.)

NOT NULL UNIQUE
Establishes a unique index on the column. (See "UNIQUE" in the "unique-block" section for a definition of a unique index.)

FOR SBCS DATA

Indicates the column will contain single-byte characters.

FOR MIXED DATA

Indicates the column might contain values that have a mixture of single-byte or double-byte characters.

FOR BIT DATA

Indicates that the values of a character column are not associated with a coded character set and therefore are never converted. For example, the bit pattern of the data should not be modified when moving table data between ASCII and EBCDIC environments. The database manager sets the SUBTYPE column in the SYSCOLUMNS catalog table to 'B' when this option is specified.

CCSID integer
Uniquely identifies an encoding scheme and one or more pairs of character sets and code pages, for either character or graphic data.

Depending on the specification of subtypes and CCSIDs, the database manager assigns different values:

  • If either SBCS or mixed data is specified, then the database default CCSID for the subtype is assigned.
  • If a CCSID is specified, then the subtype that matches the CCSID is assigned.
  • If neither SBCS nor mixed data is specified and a CCSID is also not specified, then first the default subtype is assigned; then the database default CCSID for that subtype is assigned.
  • If graphic data is specified without a CCSID, then the database default CCSID for graphic data is assigned.

The choice of CCSID, including allowing it to default, may significantly affect performance. For performance implications related to CCSID, consult the DB2 Server for VSE & VM Performance Tuning Handbook manual.

fieldproc-block

FIELDPROC program_name

Names a field procedure for the column. Use a field procedure only with a short string column. The column has no field procedure if you omit FIELDPROC.

constant
Is a parameter of the field procedure. A parameter list is optional. The number of parameters and the data type of each are determined by the field procedure. The maximum length of the parameter list is 254 bytes, including commas, but excluding insignificant blanks and the delimiting parentheses after blank compression occurs.

primary-key-block

PRIMARY KEY
Is a set of column values in the table that enforces a unique constraint. Only one primary key is allowed in a parent table. Primary key values must be unique and must be defined as NOT NULL.

Defining a primary key on a table sets up the table to be referenced by another table's foreign key to establish a referential constraint.

column_name
Identifies the column or columns that comprise the primary key. Each column_name must be an unqualified name that identifies a column of the table, and that column must be defined as NOT NULL. No column in a primary key can contain a long string. The same column cannot be specified more than once.

ASC
Creates the primary key such that the values from this column are arranged in ascending order. This is the default.

DESC
Creates the primary key such that the values from this column are arranged in descending order.

PCTFREE
Is the percentage of space in each index page reserved for later insertions and updates of the primary key. The integer can range from 0 to 99, but for practical purposes should not exceed 50. Increasing PCTFREE causes the index to take up more space, but reduces the time required to insert or update primary key rows of the indexed table.

referential-constraint-block

FOREIGN KEY
Defines a foreign key which consists of one or more columns in a dependent table that together must take on a value that exists in the primary key of the related parent table. The columns in the dependent table may contain nulls. If any of the columns contain a null value, the foreign key is considered null.

constraint_name
Provides a name for the referential constraint. You cannot use a constraint_name more than once in the same table. Although the database manager generates a constraint_name if you do not specify one, you should specify your own constraint_name to make it easier for you to drop, activate, and deactivate the foreign key.

column_name
Identifies the column or columns that comprise the foreign key. Each column_name must be an unqualified name that identifies a column of the table. The data type and length of foreign key columns must match the data type and length of the primary key columns. Only the null attribute of a foreign key column may be different. The same column cannot be specified more than once.

REFERENCES table_name

Specifies the name of the parent table involved in the referential constraint. The table_name cannot identify the table that is being created. The identified table must already exist and cannot be the system catalog table.

ON DELETE
Defines the delete rule to be followed when a row is deleted from the parent table in a relationship.

RESTRICT
Prevents deletion of a parent row until all the dependent rows have been deleted. RESTRICT is the default value.

CASCADE
Causes all dependent rows to be deleted also.

SET NULL
Sets to null all columns of the foreign keys in each dependent row that can contain nulls. At least one column of the foreign key in the dependent table must be able to contain nulls.

The following restriction for ON DELETE is checked when a table is created.

  • If a table has more than one referential constraint referencing the same parent, all the delete rules on those constraints must be the same and must not be SET NULL.
  • If a table is delete-connected to the same parent through multiple paths, all of the delete rules on a path, except for the last one, must be CASCADE. The last constraint on all paths must be the same, and must not be SET NULL.

unique-block

UNIQUE
Adds a unique index for the column or columns specified. If there are duplicates in the values of the columns, then a unique constraint is not added.

constraint_name
Provides a name for the unique constraint. You cannot use the same constraint_name more than once in the same table. Although the database manager generates a constraint_name if you do not specify one, you should specify your own constraint_name to make it easier for you to drop, activate, and deactivate the unique constraint.

column_name
Identifies the column or columns that comprise the unique key. Each column_name must be an unqualified name that identifies a column of the table, and that column must be defined as NOT NULL. No column in a unique constraint can be nullable. You cannot specify the same column more than once. These columns should not be the same as that of a primary key in the same table.

ASC
Creates the unique key such that the values from this column are arranged in ascending order. This is the default.

DESC
Creates the unique key such that the values from this column are arranged in descending order.

PCTFREE
Is the percentage of space in each index page reserved for later insertions and updates of unique keys. The integer may range from 0 to 99, but for practical purposes should not exceed 50. Increasing PCTFREE causes the index to take up more space, but reduces the time required to insert or update unique keys.

IN dbspace_name

The name of the dbspace into which the table is to be placed. The dbspace must exist at the application server. The default qualifier portion of dbspace_name is the authorization ID of the statement. If dbspace_name is omitted, the table will be created in one of the owner's private dbspaces (if the owner does not have any private dbspace, an error condition will result).

A newly created table is placed in one of the existing dbspaces of the database according to the following rules:

  1. Specifying a dbspace_name in the CREATE TABLE statement puts the table into the named dbspace. The owner of the dbspace must be either the user who preprocessed the current program, or PUBLIC. If you have DBA authority, you can create a table in a private dbspace of any user by qualifying the dbspace_name with its owner's user ID, as follows:
       CREATE TABLE ... IN SCOTT.DSP3
    
  2. Not specifying a dbspace_name in the CREATE TABLE statement puts the table into any private dbspace owned by the authorization ID who preprocessed the program. Consider the following case:
    1. The person who preprocessed the program has DBA authority.
    2. No dbspace is specified.
    3. The table name is qualified with an authorization_name.

    The database manager places the table into any private dbspace owned by the specified authorization ID. If there is no such dbspace, an error condition results.

  3. If the dbspace_name is not qualified, the database manager will not place the table into a nonrecoverable dbspace by default. Specify the dbspace_name to create a table in a nonrecoverable dbspace.
  4. If both the table_name and the dbspace_name are qualified, but are not qualified with the same authorization_name, and the authorization ID who preprocessed the program has DBA authority, the database manager uses both qualifiers. That is, if JIM has DBA authority, he may create table KELLI.SUPPLIERS in JOE.SPACE1.

    Table 9 summarizes where a table is placed depending on what is specified. X represents the user ID of the person who preprocessed the program. X is denoted as optional below because if no user ID is specified, the creator always defaults to the user ID of the person who preprocessed the program (X). Y represents some other user ID.

    Table 9. Default table placement when user X preprocesses the program.
    DBA Authority Needed? Table Creator Table Name DBSPACE Owner DBSPACE Name Database Manager Action
    No X A     User X creates X.A in a private dbspace owned by X.
    Yes Y A     User X creates Y.A in any private dbspace owned by Y.
    No X A X B User X creates X.A in X.B1
    Yes   A Y B User X creates X.A in Y.B
    Yes Y A   B User X creates Y.A in Y.B1
    Yes Y A Z B User X creates Y.A in Z.B

    1
    If there is no PRIVATE DBSPACE B, but there is PUBLIC DBSPACE B, the PUBLIC DBSPACE will be used.

    Concatenate the desired authorization_names to both the table_name and the dbspace_name to avoid confusion. This concatenation always identifies both the owner of the table and where the table will be placed.

DATA CAPTURE
Specifies if log records for this table should contain the full before image (DATA CAPTURE CHANGES) or the partial before image (DATA CAPTURE NONE) for UPDATE operations. If this option is not specified, it defaults to DATA CAPTURE NONE. If DataPropagator Capture is being used to capture changes to this table, DATA CAPTURE CHANGES must be specified. If DataPropagator Capture is not being used to capture updates to this table, DATA CAPTURE NONE should be specified to reduce the amount of data logged for updates to this table.

NONE
Include the partial before image in the log records for UPDATE operations. If DataPropagator Capture is not being used to capture updates to this table, DATA CAPTURE NONE should be specified to reduce the amount of data logged for updates to this table.

CHANGES
Include the full before image in the log records for UPDATE operations. If DataPropagator Capture is being used to capture changes to this table, DATA CAPTURE CHANGES must be specified.

Notes

Once a table has been created, the data types of its columns may not be changed, and columns may not be deleted from a table. However, new columns may be added to the table (with the ALTER TABLE statement).

Byte counts

The sum of the byte counts of the columns must not be greater than 4077. The list that follows gives the byte counts of columns by data type for columns that do not allow null values. For a column that allows null values the byte count is one more than shown in the list.

Data Type
Byte Count

INTEGER
4

SMALLINT
2

FLOAT( n)
If n is from 1 to 21, the byte count is 4. If n is from 22 to 53, the byte count is 8.

DECIMAL( p, s)
(p/2 + 1), rounded down to an integer.

CHAR( n)
n

VARCHAR( n)
n+2, or 6 if n>254

LONG VARCHAR
6

DATE
4

TIME
3

TIMESTAMP
10

GRAPHIC( n)
2n

VARGRAPHIC( n)
2n+2, or 6 if n>127

LONG VARGRAPHIC
6

Dbspace use for long string columns

Actual data for a long string column is stored in its own internal table in the dbspace. Thus, each table that contains long string columns uses one of the available 255 tables in the dbspace.

Tables as part of a referential structure

Tables that are part of a referential structure must be defined in DBSPACEs that are in the same type of storage pool. That is, both parent and dependent tables in the same referential structure must be in DBSPACEs that are in either a recoverable storage pool or a nonrecoverable storage pool. If the tables are not in the same type of storage pool, any attempt to define or change a referential constraint will produce an error.

Examples

Example 1

Given that you have DBA authority, create a table named 'ROSSITER.INVENTORY' with the following columns:

part number
integer between 1 and 9,999, must be present
description
character of length 1 to 24
quantity on hand
integer between 0 and 100,000

  CREATE TABLE ROSSITER.INVENTORY
       (PARTNO         SMALLINT     NOT NULL,
       DESCRIPTION    VARCHAR(24),
       QONHAND        INT)

Example 2

Given that you have DBA authority, create the SITE1_SUPPLIERS table in the PUBLIC dbspace SPACE3 with the following columns and make KRISTEL the owner of the table:

supplier number
integer between 1 and 99, must be present
name
character of length 15
address
character of length 1 to 35

  CREATE TABLE KRISTEL.SITE1_SUPPLIERS
       (SUPPNO         SMALLINT     NOT NULL,
     NAME           CHAR(15),
     ADDRESS        VARCHAR(15) )
    IN "PUBLIC".SPACE3

Example 3

Create the EQUIPMENT table in one of your private dbspaces with the following columns:

equipment number
integer between 0100000 and 8999999
equipment description
varying length string of up to 50 characters
location
varying length string of up to 50 characters
equipment owner
the number of the department that owns this equipment, null if not owned by any department

Ensure there is a unique entry in the table for each piece of equipment and order the entries in ascending order by equipment number (EQUIP_NO).

Also define a referential constraint with the table so that the equipment owner (EQUIP_OWNER) must be a department (DEPTNO) that is present in the DEPARTMENT table. If a department is removed from the DEPARTMENT table, the equipment owner values for all equipment owned by that department should become unassigned (that is, set to null). Give the constraint a name of DEPT_EQUIP.

  CREATE TABLE EQUIPMENT
  (EQUIP_NO INT      NOT NULL,
               EQUIP_DESC     VARCHAR(50),
               LOCATION       VARCHAR(50),
               EQUIP_OWNER    CHAR(3),
               PRIMARY KEY(EQUIP_NO),
               FOREIGN KEY DEPT_EQUIP (EQUIP_OWNER)
                 REFERENCES DEPARTMENT
                 ON DELETE SET NULL )

Example 4

On a DB2 Server for VM or DB2 Server for VSE application server with mixed data supported and with a default character subtype (that is, CHARSUB) of mixed, create a table named 'MAPS' in one of your private dbspaces. This table is designed to be maintained from a DB2 for OS/2 application requester. The table is to have the following columns (all values must be present):
Column Description Data Stored
MAP_NUMBER map number 7 SBCS characters (to be converted to EBCDIC)
LAST_UPD last update date
DESC description up to 40 ASCII mixed (to be converted to EBCDIC)
MAP the map up to 4000 bytes (not to be converted to EBCDIC)

  CREATE TABLE MAPS
              (MAP_NUMBER CHAR(7)  FOR SBCS DATA NOT NULL,
              LAST_UPD       DATE  NOT NULL,
              DESC           VARCHAR(40)  NOT NULL,
              MAP            VARCHAR(4000)  FOR BIT DATA NOT NULL)

Example 5

Similar to example 4, except that the default character subtype in the system is SBCS.

  CREATE TABLE MAPS
         (MAP_NUMBER CHAR(7) NOT NULL,
         LAST_UPD       DATE                        NOT NULL,
         DESC           VARCHAR(40)  FOR MIXED DATA NOT NULL,
         MAP            VARCHAR(4000)       FOR BIT DATA NOT NULL)

Example 6

Similar to example 5, except that not only is the default character subtype SBCS but the default CCSIDs for both SBCS and mixed are not those required in the table (the table requires an SBCS CCSID of 290 and a mixed CCSID of 5026).

  CREATE TABLE MAPS
         (MAP_NUMBER     CHAR(7)   CCSID 290    NOT NULL,
         LAST_UPD       DATE   NOT NULL,
         DESC           VARCHAR(40)   CCSID 5026   NOT NULL,
         MAP            VARCHAR(4000)        FOR BIT DATA NOT NULL)

Example 7

Create a table and include the partial before image on UPDATE log records because DataPropagator Capture is not capturing updates for this table:

  CREATE TABLE SALARY1 .....
           OR
  CREATE TABLE SALARY1 .....
     DATA CAPTURE NONE

Example 8

Create a table and include the full before image on UPDATE log records because DataPropagator Capture requires this information for update log records:

  CREATE TABLE SALARY2 .....
     DATA CAPTURE CHANGES

CREATE VIEW

The CREATE VIEW statement creates a view on one or more tables or views.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

If the specified view name includes a qualifier that is not the same as the authorization ID of the statement, the privileges held by the authorization ID of the statement must include DBA authority. If the view name is qualified by an identifier that is not your authorization ID, you must have DBA authority.

Syntax



>>-CREATE VIEW--view_name----+----------------------------+----->
                             |    .-,--------------.      |
                             |    V                |      |
                             '-(-----column_name---+---)--'
 
>----AS--subselect--+-------------------+----------------------><
                    '-WITH CHECK OPTION-'
 

Description

view_name
Provides a name for the view. The name, including the implicit or explicit qualifier, must not identify a table, view, or synonym that already exists at the application server.

The implicit or explicit qualifier of the view_name is the owner of the view. The owner always acquires the SELECT privilege on the view, and the authority to drop the view. The SELECT may be granted to others only if the owner has the authority to grant the SELECT privilege on every table or view identified in the first FROM clause of the subselect.

If the owner has the INSERT, UPDATE, or DELETE privileges on the table or view identified in the first FROM clause of subselect, then the owner also acquires these privileges on the view being created. Only the owner of the table or view identified in the first FROM clause of the subselect can grant the privilege.

(column_name,...)
Names the columns in the view. If you specify a list of column names, it must consist of as many names as there are columns in the result table of the subselect. Each column_name must be unique and unqualified. If you do not specify a list of column names, the columns of the view inherit the names of the columns of the result table of the subselect.

You must specify a list of column names if the result table of the subselect has duplicate column names or an unnamed column (a column derived from a constant, function, or expression).

AS subselect
Defines the view. At any time, the view consists of the rows that would result if the subselect were processed. Note that the subselect is not processed when the view is created, which means that semantic errors (for example, specifying "WHERE COL = '10'" when COL is a decimal column) are not detected until the view is used. To determine whether a statement contains semantic errors, you can enter a 'SELECT *' against the view after creating it.

subselect must not reference host variables. For an explanation of subselect, see Chapter 5, Queries.

WITH CHECK OPTION
Specifies the constraint that every row of the view must conform to the search condition of the view. The constraint is enforced by the database manager whenever rows of the view are inserted or updated. If the search condition is not true for any inserted or updated row, an error is returned, and no rows are inserted or updated.

The search condition of a view is the search condition specified in the first WHERE clause of the subselect used to define the view.

WITH CHECK OPTION must not be specified if the view is read-only or if its search condition includes a subquery. WITH CHECK OPTION is ignored if the view is updateable but does not have a search condition. If WITH CHECK OPTION is specified for an updateable view that does not allow inserts, the constraint only applies to updates.

If WITH CHECK OPTION is omitted, the search condition of the view is not used in the checking of any insert or update operations. The view can then be used to insert a row that does not conform to the search condition of the view and to update a row so that it no longer conforms to the search condition of the view. A row that does not conform to the search condition of a view cannot be retrieved using that view. It is also possible for this situation to exist when WITH CHECK OPTION is specified; this can happen when the view is directly or indirectly dependent on a view that was defined without the constraint.

The WITH CHECK OPTION constraint on view V is inherited by any updateable view that is directly or indirectly dependent on V. Thus, if an updateable view is defined on V, the constraint on V also applies to that view, regardless of whether WITH CHECK OPTION is specified in the definition of that view.

Consider the following updateable views:

When a row of V5 or V4 is inserted or updated, it is checked against the conjunction of the search conditions of V4 and V2. When a row of V3 or V2 is inserted or updated, it is checked against the search condition of V2. When a row of V1 is inserted or updated, it is not checked against any search condition.

FOR UPDATE OF, ORDER BY, and UNION cannot be used in the definition of a view.

Notes

Read-only views

A view is read-only if its definition involves any of the following:

A read-only view cannot be the object of an INSERT, UPDATE, or DELETE statement. Note that the fact that a table contains expressions does not make it a read only view. As long as the expressions reference a single base table, such a view can be used to delete rows from the base table or to update columns that are defined without expressions. Rows can also be inserted into such views if the columns defined as expressions are nullable.

If you use a 'SELECT *' clause in the view definition and then you add a column to an underlying table (with the ALTER TABLE statement), the new column will not appear in the view.

There is no specific number for the limit on the number of columns in a view, because it depends on many factors which affect this limit. A view of up to 140 columns should work in most situations.

Examples

Example 1

Create a view named MA_PROJ upon the PROJECT table that contains only those rows with a project number (PROJNO) starting with the letters 'MA'.

  CREATE VIEW MA_PROJ
  AS SELECT * FROM PROJECT
    WHERE SUBSTR(PROJNO, 1, 2) = 'MA'

Example 2

Create a view as in example 1, but select only the columns for project number (PROJNO), project name (PROJNAME) and employee in charge of the project (RESPEMP).

  CREATE VIEW MA_PROJ
  AS SELECT PROJNO, PROJNAME, RESPEMP
    FROM PROJECT
         WHERE PROJNO LIKE 'MA____'

Example 3

Create a view as in example 2, but, in the view, call the column for the employee in charge of the project IN_CHARGE.

  CREATE VIEW MA_PROJ
  (PROJNO, PROJNAME, IN_CHARGE)
    AS SELECT PROJNO, PROJNAME, RESPEMP FROM PROJECT
         WHERE SUBSTR(PROJNO, 1, 2) = 'MA'

Note: Even though you are changing only one of the column names, the names of all three columns in the view must be listed in the parentheses that follow MA_PROJ.

Example 4

Create a view named PRJ_LEADER that contains the first four columns (PROJNO, PROJNAME, DEPTNO, RESPEMP) from the PROJECT table together with the last name (LASTNAME) of the person who is responsible for the project (RESPEMP). Obtain the name from the EMPLOYEE table by matching EMPNO in EMPLOYEE to RESEMP in PROJECT.

  CREATE VIEW PRJ_LEADER
  AS SELECT PROJNO, PROJNAME, DEPTNO, RESPEMP, LASTNAME
         FROM PROJECT, EMPLOYEE
         WHERE RESPEMP = EMPNO

Example 5

Create a view as in example 4, but in addition to the columns PROJNO, PROJNAME, DEPTNO, RESEMP and LASTNAME, show the total pay (SALARY + BONUS +COMM) of the employee who is responsible. Also select only those projects with mean staffing (PRSTAFF) greater than one.

  CREATE VIEW PRJ_LEADER (PROJNO, PROJNAME, DEPTNO, RESPEMP, LASTNAME, TOTAL_PAY )
    AS SELECT PROJNO, PROJNAME, DEPTNO, RESPEMP, LASTNAME, SALARY+BONUS+COMM
         FROM PROJECT, EMPLOYEE
         WHERE RESPEMP = EMPNO AND PRSTAFF > 1

Example 6

This example shows something that can happen when a view defined WITH CHECK OPTION depends on a view defined without this option. In this case, a view named VV depends on a view named WW, and WW depends on the EMPLOYEE sample table. The view definitions are as follows:

  CREATE VIEW WW
    AS SELECT * FROM EMPLOYEE
         WHERE SALARY < 35000.00
 
  CREATE VIEW VV
    AS SELECT * FROM WW
         WHERE SALARY > 30000.00
         WITH CHECK OPTION

Assume both views have a single owner, who uses VV in the following UPDATE statement:

  UPDATE VV SET SALARY = SALARY + 5000.00

The update applies to every row in which SALARY is greater than 30000 but less than 35000. After the update, all rows that were visible to WW have salaries greater than 35000. Such salaries conform to the search condition of VV but not to that of WW. Even so, because WW is not defined WITH CHECK OPTION, all these rows are updated. As a result, any row in EMPLOYEE that was visible to VV is now invisible to WW and is therefore also invisible to VV.

DECLARE CURSOR

The DECLARE CURSOR statement defines the cursor through which a user may OPEN, FETCH, PUT, or CLOSE the results of a statement prepared using PREPARE. There are two types of cursor:

Invocation

This statement can only be embedded in an application program. It is not an executable statement.

Authorization

No authorization is required to use this statement except in the case of FORTRAN. Programs in these languages will fail if the authorization ID is not the same as that used to preprocess the program.

To use the OPEN statement for the cursor, the privileges held by the authorization ID of the statement are outlined below.

The cursor must always be linked to a select-statement or an insert-statement. This linked statement may be identified in one of three ways. The authorization required to manipulate the cursor varies accordingly.

  1. If the statement is a fullselect of the form identified by select-statement, then the authorization ID is the one that is used to preprocess the program. This authorization ID must have SELECT privileges on every table and view identified in the SELECT.
  2. If the statement is an INSERT (using VALUES), then the authorization ID is the one that preprocesses the program. This authorization ID must have INSERT authority on that table.
  3. If the statement is a prepared SELECT or INSERT (using VALUES) statement named by a statement_name clause, then the authorization ID is the run-time authorization ID. Depending on whether the statement to be prepared is a SELECT or INSERT (using VALUES), this authorization ID must have appropriate SELECT or INSERT privileges.

Someone with DBA authority may do any of the above.

Syntax



>>-DECLARE---cursor-name---CURSOR----+----------------+--FOR---->
                                     +-WITH RETURN----+
                                     |           (1)  |
                                     '-WITH HOLD------'
 
>-----+-select-statement-+-------------------------------------><
      '-statement-name---'
 


Notes:


  1. Note that DB2 Server for VSE & VM does not support CURSOR WITH
    HOLD.


Description

cursor_name
Provides a name for the cursor. The name must not be the same as the name of another cursor declared in your source program. In REXX, cursor_name must not be the same as a statement_name prepared in the program.

A cursor in the open state designates an active set (for query cursors this is also known as the cursor's result table)

and a position relative to the rows of that active set. The active set is specified by the SELECT or INSERT statement of the cursor.

A program may contain many DECLARE CURSOR statements that define different cursors and associate them with different queries or inserts. During processing of a program, several of these cursors may be in the open state at one time. The DECLARE CURSOR statement that defines a cursor must occur earlier in the program than any cursor manipulation statement operating on that cursor. The DECLARE CURSOR statement does not result in any actual processing when the program is run (that is, it does not automatically open the cursor).

The DECLARE CURSOR statement must precede all statements that explicitly reference the cursor by name.

Following is a description of each form of DECLARE CURSOR.

DECLARE CURSOR for SELECT

select-statement
Specifies the SELECT statement of the cursor.

The select-statement must not include parameter markers, but can include references to host variables. In host languages, other than assembler and REXX, the declarations of the host variables must precede the DECLARE CURSOR statement in the source program. Host variable declarations can follow the DECLARE CURSOR statement in assembler and host variables are not declared at all in REXX.

The result table is read-only if any of the following are true:

If the select-statement of a cursor contains CURRENT DATE, CURRENT TIME, or CURRENT TIMESTAMP, all references to these special registers will yield the same value on each FETCH. This value is determined when the cursor is opened.

Examples

Example 1  In a PL/I program, use the cursor C1 to fetch the values for a given project (PROJNO) from the first four columns of the EMP_ACT table a row at a time and put them into the following host variables: EMP (char(6)), PRJ (char(6)), ACT (smallint), and TIM (dec(5,2)). Obtain the value of the project to search for from the host variable SEARCH_PRJ (char(6)).

  EXEC SQL  BEGIN DECLARE SECTION;
    DCL  EMP              CHAR(6);
    DCL  PRJ              CHAR(6);
    DCL  SEARCH_PRJ       CHAR(6);
    DCL  ACT              BINARY FIXED(15);
    DCL  TIM              DEC    FIXED(5,2);
  EXEC SQL  END DECLARE SECTION;
    .
    .
    .
  EXEC SQL  DECLARE C1 CURSOR FOR
              SELECT EMPNO, PROJNO, ACTNO, EMPTIME
                FROM EMP_ACT
                WHERE PROJNO = :SEARCH_PRJ;
 
  EXEC SQL  OPEN C1;
 
  EXEC SQL  FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM;
 
  IF SQLSTATE = '02000' THEN
    CALL DATA_NOT_FOUND;
  ELSE
    DO WHILE (SUBSTR(SQLSTATE,1,2) = '00' | SUBSTR(SQLSTATE,1,2) = '01');
      EXEC SQL  FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM;
    END;
 
  EXEC SQL  CLOSE C1;
    .
    .
    .

Example 2  In a PL/I program, declare a cursor named INCREASE to return from the EMPLOYEE table all the employee numbers (EMPNO), surnames (LASTNAME) and price (SALARY increased by 10 percent) of people who have the job of clerk (JOB). Order the result table in descending order by the increased salary.

  EXEC SQL  DECLARE INCREASE CURSOR FOR
              SELECT EMPNO, LASTNAME, SALARY * 1.1
                FROM EMPLOYEE
                WHERE JOB = 'CLERK'
                ORDER BY 3 DESC;

Example 3  In a PL/I program, declare a cursor named UP_CUR to update all the columns of the DEPARTMENT table.

  EXEC SQL  DECLARE UP_CUR CURSOR FOR
              SELECT *
                FROM DEPARTMENT
                FOR UPDATE OF DEPTNO, DEPTNAME, MGRNO, ADMRDEPT;

Example 4  In a PL/I program, declare a cursor named DEL_CUR to examine, and potentially delete, rows in the DEPARTMENT table.

  EXEC SQL  DECLARE DEL_CUR CURSOR FOR
              SELECT *
                FROM DEPARTMENT;

DECLARE CURSOR for INSERT

insert-statement
This is an INSERT using VALUES statement as defined with the INSERT statement. The insert-statement must not include parameter markers, but can include references to host variables. In host languages, other than assembler and REXX, the declarations of the host variables must precede the DECLARE CURSOR statement in the source program. In assembler host variable declarations can follow the DECLARE CURSOR statement. In REXX, host variables are not declared at all.

Once a cursor has been defined and opened, you may insert new rows into the table using the PUT statement.

Example 5

This example shows portions of a pseudo COBOL program. In this program, use the cursor C2 to insert a row into the DEPARTMENT table based on the values in the host variables DPT_NO (char(3), DPT_NM (varchar(29)), MGR_NO (char(6)), and DPT_AD (char(3)).

  * in working storage:
      EXEC SQL  BEGIN DECLARE SECTION  END-EXEC.
        77 DPT-NO           PIC X(3).
        77 MGR-NO           PIC X(6).
        77 DPT-AD           PIC X(3).
        01 DPT-NM.
           49 DPT-NM-LEN    PIC S9(4) COMP  VALUE +29.
           49 DPT-NM-VAL    PIC X(29)       VALUE SPACES.
      EXEC SQL  END DECLARE SECTION  END-EXEC.
 
  * at start of processing:
      EXEC SQL  DECLARE C2 CURSOR FOR
                  INSERT INTO DEPARTMENT
                    VALUES (:DPT-NO, :DPT-NM, :MGR-NO, :DPT-AD)  END-EXEC.
      EXEC SQL  OPEN C2  END-EXEC.
 
  * loop as many times as necessary:
  *   solicit values from screen and assign to DPT-NO, DPT-NM, MGR-NO, DPT-AD
      EXEC SQL  PUT C2  END-EXEC.
 
  * at end of processing
      EXEC SQL  CLOSE C2  END-EXEC.

DECLARE CURSOR for Dynamic Queries

statement_name
Identifies a SELECT or INSERT statement defined in a PREPARE statement. (When communicating with an application server that is not DB2 Server for VM or DB2 Server for VSE, this restriction might not be enforced.) The DECLARE CURSOR statement and its associated PREPARE statement must be in the same logical unit of work. They may be specified in either order, except in FORTRAN programs when the string-constant form of the PREPARE statement is used. For information on this restriction, see PREPARE.

Example 6

This example is similar to Example 1 under DECLARE CURSOR for SELECT. The difference is that the right hand side of the WHERE clause is to be specified dynamically; thus the entire select-statement is placed into a host variable and dynamically prepared.

  EXEC SQL  BEGIN DECLARE SECTION;
    DCL  EMP              CHAR(6);
    DCL  PRJ              CHAR(6);
    DCL  SEARCH_PRJ       CHAR(6);
    DCL  ACT              BINARY     FIXED(15);
    DCL  TIM              DEC        FIXED(5,2);
    DCL  SELECT_STMT      CHAR(200)  VARYING;
  EXEC SQL  END DECLARE SECTION;
 
 
  SELECT_STMT = 'SELECT EMPNO, PROJNO, ACTNO, EMPTIME ' ||
                  'FROM EMP_ACT ' ||
                  'WHERE PROJNO = ?';
    .
    .
    .
  EXEC SQL  PREPARE SELECT_PRJ FROM :SELECT_STMT;
 
  EXEC SQL  DECLARE C1 CURSOR FORSELECT_PRJ;
 
  EXEC SQL  OPEN C1 USING :SEARCH_PRJ;
 
  EXEC SQL  FETCH C1 INTO :EMP, :PRJT, :ACT, :TIM;
 
  IF SQLSTATE = '02000' THEN
    CALL DATA_NOT_FOUND;
  ELSE
    DO WHILE (SUBSTR(SQLSTATE,1,2) = '00' | SUBSTR(SQLSTATE,1,2) = '01');
      EXEC SQL  FETCH C1 INTO :EMP, :PRJ, :ACT, :TIM;
    END;
 
  EXEC SQL  CLOSE C1;
    .
    .
    .

DECLARE CURSOR WITH RETURN

WITH RETURN
Specifies that the cursor, if declared in a stored procedure, can return a result set to a caller.

Example 7

The following statements could be included in a stored procedure. If the cursors are opened and not closed, the result sets are returned to the requester.

   EXEC SQL DECLARE CURS1 CURSOR WITH RETURN FOR
     SELECT A.X,Y,Z FROM TABLEX A, TABLEY B WHERE A.X = B.X
 
   EXEC SQL DECLARE CURS2 CURSOR WITH RETURN FOR STMT1

Overall Notes

The scope of cursor_name is the source program in which it is defined; that is, the program submitted to the preprocessor. Thus, you can only reference a cursor by statements that are preprocessed with the cursor declaration. For example, a program called from another separately preprocessed program cannot use a cursor that was opened by the calling program.

The NOFOR Option

The NOFOR preprocessor option concerns the use of the UPDATE clause when a cursor is declared for a static (embedded) query. With NOFOR in effect, this clause is optional. When the clause is used, updates are restricted to the columns designated within it. NOFOR is only useful when the UPDATE statements are static. See the DB2 Server for VSE & VM Application Programming manual for more details on the NOFOR preprocessor option.

Extended DECLARE CURSOR

The Extended DECLARE CURSOR statement defines the cursor through which a user may OPEN, FETCH, PUT, or CLOSE the results of a statement prepared using Extended PREPARE. There are two types of cursor:

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the statement must have one of the following:

Syntax



>>-DECLARE--cursor_variable--CURSOR FOR--section_variable------->
 
>----IN--package_spec------------------------------------------><
 

Description

cursor_variable
Provides a name for the cursor. The name placed into cursor_variable must be unique within the logical unit of work in which it is used.

CURSOR FOR section_variable
Identifies a select-statement or insert-statement defined in an Extended PREPARE statement. A cursor need not be declared in the same logical unit of work or program in which the statement was prepared.

IN package_spec
Identifies the package in which the referenced SQL statement resides. The package_spec must identify a package that exists at the application server.

Notes

Cursors are associated with a prepared select-statement or insert-statement by the value returned in the section_variable and the package_spec specified in the Extended DECLARE CURSOR statement. Extended DECLARE CURSOR may be used for any select-statement or insert-statement in a package created using the CREATE PACKAGE statement.

A cursor name used in a WHERE CURRENT OF clause of a DELETE statement or an UPDATE statement cannot be specified from a host variable. Therefore, at execution time, the content of cursor_name in the Extended DECLARE CURSOR statement must be the same as the cursor_name hard-coded in the WHERE CURRENT OF clause.

After the Extended DECLARE CURSOR statement is entered, a cursor is established; the cursor can then be opened and used to retrieve or insert rows through the Extended OPEN, FETCH, and PUT statements.

Examples

DECLARE :CURSOR1 CURSOR FOR :STMID IN :USERID.:PACKNAME

DELETE

The DELETE statement deletes rows from a table or view. Deleting a row from a view deletes the row from the table on which the view is based.

There are two forms of this statement:

Invocation

A Searched DELETE statement can be embedded in an application program or issued interactively. A Positioned DELETE must be embedded in an application program. Both Searched DELETE and Positioned DELETE are executable statements that can be dynamically prepared.

A Positioned DELETE in FORTRAN, and programs prepared using extended dynamic SQL cannot be used with the DRDA protocol.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

The DELETE privilege on a view is only inherent in DBA authority. Ownership of a view does not necessarily include the DELETE privilege on the view because the privilege may not have been granted when the view was created, or it may have been granted, but subsequently revoked.

If the search-condition includes a subquery, the privileges designated by the authorization ID of the statement must also include the SELECT privilege on every table or view identified in the subquery. The privilege may have been explicitly granted or may be inherent in another privilege. The SELECT privilege on a table or view is inherent in DBA authority and ownership of a table or view.

Syntax



Searched delete (I,P)

>>-DELETE FROM----+-table_name-+--+------------------+---------><
                  '-view_name--'  '-correlation_name-'
 
>>-+--------------------------+---+---------------+------------><
   '-WHERE--search_condition--'   '-WITH--+-RR-+--'
                                          '-CS-'
 

Positioned delete (P)

>>-DELETE FROM----+-table_name-+-------------------------------->
                  '-view_name--'
 
                      (1)
>----WHERE CURRENT OF-------cursor_name------------------------><
 


Notes:



  1. A Positioned DELETE in FORTRAN, and programs prepared using Extended
    dynamic SQL cannot be used with DRDA protocol.


Description

FROM table_name  or  view_name
Identifies the table or view from which rows are to be deleted. The name must identify a table or view that exists at the application server, but must not identify a catalog table, a view of a catalog table, or a read-only view. (For an explanation of read-only views, see CREATE VIEW.)
Note:Someone with DBA authority may delete rows from a few of the catalog tables. See Updateable Columns.

correlation_name
Can be used within the search_condition to designate the table or view. (For an explanation of correlation_name, see Chapter 3, "Language Elements".)

WHERE
Specifies the rows to be deleted. You can omit the clause, give a search condition, or name a cursor. If you omit the clause, all rows of the table or view are deleted.

search_condition
Is any search condition as described in Chapter 3, "Language Elements". Each column_name in the search condition, other than in a subquery, must name a column of the table or view.

The search_condition is applied to each row of the table or view and the deleted rows are those for which the result of the search_condition is true.

If the search condition contains a subquery, the subquery can be thought of as being processed each time the search condition is applied to a row, and the results used in applying the search condition. In actuality, a subquery with no correlated references is processed once, whereas a subquery with a correlated reference may have to be processed once for each row.

The following restriction is enforced when a DELETE statement is prepared or preprocessed with a WHERE clause containing a subquery. Let T2 denote the object table of a DELETE statement, and let T1 denote a table that is referenced in the FROM clause of a subquery of that statement, T1 must not be a table that can be affected by the DELETE on T2. The following example demonstrates the relationships.

   DELETE FROM T2 WHERE FIELD2 IN (SELECT FIELD1 FROM T1);

The following rules apply to the above situation:

  • T1 and T2 must not be the same table.
  • T1 must not be a dependent of T2 in a relationship with a delete rule of CASCADE or SET NULL.
  • T1 must not be a dependent of another table T3 in a relationship with a delete rule of CASCADE or SET NULL if deletes of T2 cascade to T3.

WITH
Specifies the isolation level used when locating the rows to be deleted by the statement.

RR
Repeatable read

CS
Cursor stability

The default isolation level of the statement is the isolation level of the package. WITH can only be specified on a SEARCHED delete; it is incompatible with the WHERE CURRENT OF clause.

CURRENT OF cursor_name
Identifies the cursor to be used in the delete operation. The cursor_name must identify a declared cursor as explained in DECLARE CURSOR. The cursor_name can be a delimited identifier. If cursor_name is a reserved word, it must be a delimited identifier.

The table or view specified must also be specified in the FROM clause of the SELECT statement of the cursor, and the result table of the cursor must not be read-only. (For an explanation of read-only result tables, see DECLARE CURSOR.)

When the DELETE statement is processed, the cursor must be positioned on a row; that row is the one deleted. The cursor goes into a between state in which it remains open but has no current row until you reposition it with a FETCH statement. You cannot use the cursor for further deletions or updates while it is in the between state.

To maintain data integrity between tables when data is deleted from a parent table, the database manager checks that delete rules are followed. The delete rule in a referential constraint clause defines what action should be taken by the system when a parent row is deleted. The delete rules are:

Notes

If an error occurs during the execution of any delete operation, no rows are deleted. If an error occurs during the execution of a Positioned DELETE, the position of the cursor is unchanged. However, it is possible for an error to make the position of the cursor incorrect, in which case the cursor is closed. It is also possible for a delete operation to cause a rollback, in which case the cursor is closed.

If an error occurs during the execution of a Searched DELETE, it is necessary to inspect SQLWARN6 to determine the extent of the failure. The following are current settings of SQLWARN6 along with possible responses:

  1. SQLWARN6 is set to 'S'. A severe error has occurred, leaving the system in an unusable state.
  2. SQLWARN6 is set to 'W'. An error occurred causing the LUW to be rolled back automatically. The system is still in a usable state. The application can either:
  3. SQLWARN6 is blank. An error has occurred, but the LUW is still active. For recoverable storage pools any changes made by the request have been rolled back, hence the failing request has not left any partial results in the database. For more information about recoverable storage pools, see the DB2 Server for VM System Administration or DB2 Server for VSE System Administration manual.

    The application can do one of the following:

Unless appropriate locks already exist, one or more exclusive locks are acquired by executing a successful DELETE statement. Until the locks are released, they can prevent other application processes from performing operations on the table. For further information about locking, see the description of the COMMIT WORK, ROLLBACK WORK, LOCK TABLE, and LOCK DBSPACE statements. The isolation level associated with the application process defines the degree to which rows deleted by one process are visible to other concurrent processes.

If an application process deletes a row on which any of its cursors are positioned, those cursors are positioned before the next row of their result table. Let C be a cursor that is positioned before row R (as a result of an OPEN, a DELETE through C, a DELETE through some other cursor, or a searched DELETE). In the presence of INSERT, UPDATE, and DELETE operations that affect the base table from which R is derived, the next FETCH operation referencing C does not necessarily position C on R. For example, the operation can position C on R', where R' is a new row that is now the next row of the result table.

When a DELETE statement is completed, the number of rows deleted is returned in SQLERRD(3) in the SQLCA. The value in SQLERRD(3) does not include the number of rows that were deleted as a result of a CASCADE delete rule.

SQLERRD(5) in the SQLCA shows the number of rows affected by referential constraints. It includes rows that were deleted as a result of a CASCADE delete rule and rows in which foreign keys were set to NULL as the result of a SET NULL delete rule.

If you preprocess your program with the BLOCK option, and you wish to process a Positioned DELETE dynamically, the cursor must be a SELECT...FOR UPDATE statement, even if you do not plan to process any updates with the cursor. The FOR UPDATE clause is needed to tell the database manager that blocking should be overridden when the SELECT statement is prepared. If you do not use the FOR UPDATE clause in this instance, an error will occur on your DELETE statement at execution time.

Examples

Example 1

Delete department (DEPTNO) 'D11' from the DEPARTMENT table.

  DELETE FROM DEPARTMENT
    WHERE DEPTNO = 'D11'

Example 2

Delete all the departments from the DEPARTMENT table (that is, empty the table).

  DELETE FROM DEPARTMENT

Example 3

Use a PL/I program statement to delete all the subprojects (MAJPROJ is NULL) from the PROJECT table for a department (DEPTNO) equal to that in the host variable HOSTDEPT (char(6)).

  EXEC SQL DELETE FROM PROJECT
             WHERE DEPTNO = :HOSTDEPT AND MAJPROJ IS NULL;

Example 4

Code a portion of a PL/I program that will be used to display retired employees (JOB) and then, if requested to do so, remove certain employees from the EMPLOYEE table.

  EXEC SQL  DECLARE C1 CURSOR FOR
              SELECT *
                FROM EMPLOYEE
                WHERE JOB = 'RETIRED';
 
  EXEC SQL  OPEN C1;
 
  EXEC SQL  FETCH C1 INTO ...     ;
 
  PUT ...      ;
  GET LIST (REMOVE);
  IF REMOVE = 'YES' THEN
    EXEC SQL  DELETE FROM EMPLOYEE
                WHERE CURRENT OF C1;
 
  EXEC SQL  CLOSE C1;

DESCRIBE

The DESCRIBE statement obtains information about a prepared statement. It is primarily used for describing a SELECT statement. For an explanation of prepared statements, see PREPARE.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared.

Authorization

None required. See PREPARE for the authorization required to create a prepared statement.

Syntax



>>-DESCRIBE--statement_name--INTO--descriptor_name-------------->
 
>-----+-------------------+------------------------------------><
      |        .-NAMES--. |
      '-USING--+-ANY----+-'
               +-BOTH---+
               '-LABELS-'
 

Description

statement_name
Identifies the statement about which information is to be obtained. When the DESCRIBE statement is processed, the name must identify a statement dynamically prepared in the same logical unit of work.

INTO descriptor_name
Identifies an SQL descriptor area (SQLDA). Before the DESCRIBE statement is processed, the following variable in the SQLDA must be set:

SQLN
Indicates the number of variables represented by SQLVAR. (SQLN acts as a dimension of the SQLVAR array.) SQLN must be set to a value greater than or equal to zero before the DESCRIBE statement is processed. When the USING clause is set to NAMES, LABELS, or ANY, this should specify the maximum number of expected select list items. When the USING clause is set to BOTH, twice the expected number of select list items should be specified.

When the DESCRIBE statement is processed, the database manager assigns values to the variables of the SQLDA as follows:

SQLDAID
This field serves only as an SQLDA eye-catcher. It is set to 'SQLDA' by the database manager when a DESCRIBE is first processed.

SQLDABC
16 + SQLN*44 (the length of the SQLDA).

SQLD
For a SELECT statement, the number of columns described by occurrences of SQLVAR (or, if USING BOTH was specified on DESCRIBE, twice the number of columns).

For a non-SELECT statement, 0.

SQLVAR
This is an array with an arbitrary number of occurrences of the five variables listed below. If the value of SQLD is 0, or greater than the value of SQLN, no values are assigned to occurrences of SQLVAR.

If the value of SQLD is n, where n is greater than 0 but less than or equal to the value of SQLN, values are assigned to the first n occurrences of SQLVAR so that the first occurrence of SQLVAR contains a description of the first column of the result table, the second occurrence of SQLVAR contains a description of the second column of the result table, and so on.

In cases where the USING clause is set to BOTH, the database manager returns twice as many SQLVAR entries as there are columns in the select list. Given that there are n columns, the first n SQLVAR entries are for column names and the second n entries are for column labels.

SQLTYPE
A code showing the data type of the column and whether it can contain null values. For information about the SQLTYPE codes returned following the execution of a DESCRIBE statement, see Table 22.

SQLLEN
A length value depending on the data type of the result columns. For the possible values of SQLLEN, see Table 22.

SQLDATA
Contains the CCSID of a string column, as shown in Table 23.

SQLIND
Indicates the subtype of a character column, if using the SQLDS protocol. Does not provide any information if using the DRDA protocol. For values, see Table 21.

SQLNAME
Contains the name or label associated with the column used in the select list of the DESCRIBE statement. Exceptions to this are select list items that are unnamed, such as built-in functions (SUM(SALARIES)), constants ('ABC'), and expressions (A+B+C). In these cases, position 1 of SQLNAME is blank (X'40'), and positions 3 through 30 contain a description of the unnamed field. Because a blank is not allowed in the first byte of SQL identifiers, the application program can tell whether a column name is returned.

If no column name is returned, the following rules govern the content and format of the SQLNAME field.

If the select list item involves:

  • A basic function: SQLNAME contains the name of the function followed by the column name in parentheses (for example, SUM(SALARIES)). Position 2 of SQLNAME is blank.
  • A DISTINCT object of a function: SQLNAME contains the name of the function, followed by the keyword DISTINCT and the name of the column in parentheses (for example, SUM(DISTINCT SALARIES)). If this entire description is too long to fit in positions 3 through 30 of SQLNAME, it is truncated, and position 2 is set to X'FF'.
  • An expression: SQLNAME is set to the character string EXPRESSION n, where n is a number that identifies the nth expression in the select list. For example, for the sixth expression in the select list, the database manager sets positions 3 through n of SQLNAME to EXPRESSION 6. Position 2 is blank. This rule is true even for expressions that contain built-in functions, and, because expressions include constants, for constants such as 'ABC'.
  • A function whose object is an expression: SQLNAME contains the name of the function followed by the character string EXPRESSION n in parentheses (for example, SUM(EXPRESSION 7)). Position 2 is blank.

USING
Indicates what value to assign to each SQLNAME variable in the SQLDA. If the requested value does not exist, SQLNAME is set to a length of 0.

NAMES
Assigns the name of the column. This is the default.

LABELS
Assigns the label of the column. (Column labels are defined by the LABEL ON statement.)

ANY
Assigns the column label, and if the column has no label, the column name.

BOTH
Assigns both the label and name of the column. In this case, two occurrences of SQLVAR per column are needed to accommodate the additional information. The first n occurrences of SQLVAR for each of the columns in the result table contain the column names. The second n occurrences contain the column labels.

Notes

Before the DESCRIBE statement is processed, the value of SQLN must be set to indicate how many occurrences of SQLVAR are provided in the SQLDA and enough storage must be allocated to contain SQLN occurrences. To obtain the description of the columns of the result table of a prepared SELECT statement, the number of occurrences of SQLVAR must not be less than the number of columns.

Allocating the SQLDA

Among the possible ways to allocate the SQLDA are the three described below.

First Technique

Allocate an SQLDA with enough occurrences of SQLVAR to accommodate any select list that the application will have to process. At the extreme, the number of SQLVARs could equal the maximum number of columns allowed in a result table. Having done the allocation, the application can use this SQLDA repeatedly.

This technique uses a large amount of storage that is never deallocated, even when most of this storage is not used for a particular select list.

Second Technique

Repeat the following two steps for every processed select list:

  1. Process a DESCRIBE statement with an SQLDA that has no occurrences of SQLVAR; that is, an SQLDA for which SQLN is zero. The value returned for SQLD is equal to the required number of occurrences of SQLVAR.
  2. Use the returned value of SQLD to allocate an SQLDA with enough occurrences of SQLVAR. Then process the DESCRIBE statement again, using this new SQLDA.

This technique allows better storage management than the first technique, but it doubles the number of DESCRIBE statements.

Third Technique

Allocate an SQLDA that is large enough to handle most, and perhaps all, select lists but is also reasonably small. If an execution of DESCRIBE fails because the SQLDA is too small, allocate a larger SQLDA and process DESCRIBE again. For the new SQLDA, use the value of SQLD returned from the first execution of DESCRIBE for the number of occurrences of SQLVAR.

This technique is a compromise between the first two techniques. Its effectiveness depends on a good choice of size for the original SQLDA.

Examples

In a PL/I program, process a DESCRIBE statement with an SQLDA that has no occurrences of SQLVAR. If SQLD is greater than zero, use the value to allocate an SQLDA with the necessary number of occurrences of SQLVAR and then process a DESCRIBE statement using that SQLDA.

  EXEC SQL  BEGIN DECLARE SECTION;
    DCL  STMT1_STR   CHAR(200)  VARYING;
  EXEC SQL  END DECLARE SECTION;
  EXEC SQL  INCLUDE SQLDA;
  EXEC SQL  DECLARE DYN_CURSOR CURSOR FOR STMT1_NAME;
 
  ... /* code to prompt user for a query, then to generate */
      /* a select-statement in the STMT1_STR            */
  EXEC SQL  PREPARE STMT1_NAME FROM :STMT1_STR;
 
  ... /* code to set SQLN to zero and to allocate the SQLDA */
  EXEC SQL  DESCRIBE STMT1_NAME INTO :SQLDA;
 
  ... /* code to check that SQLD is greater than zero, to set */
      /* SQLN to SQLD, then to re-allocate the SQLDA          */
  EXEC SQL  DESCRIBE STMT1_NAME INTO :SQLDA;
 
  ... /* code to prepare for the use of the SQLDA             */
  EXEC SQL  OPEN DYN_CURSOR;
 
  ... /* loop to fetch rows from result table                 */
  EXEC SQL  FETCH DYN_CURSOR USING DESCRIPTOR :SQLDA;
  .
  .
  .

Extended DESCRIBE

The Extended DESCRIBE statement obtains information about a select-statement prepared by an Extended PREPARE statement.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the statement must have one of the following:

Syntax



>>-DESCRIBE--section_variable--IN--package_spec----------------->
 
>----INTO--descriptor_name--+-------------------+--------------><
                            |        .-NAMES--. |
                            '-USING--+-ANY----+-'
                                     +-BOTH---+
                                     '-LABELS-'
 

Description

section_variable
Identifies a statement defined by an Extended PREPARE statement (see Extended PREPARE). The Extended DESCRIBE statement does not have to be in the same logical unit of work or program as the PREPARE statement that was originally used to process the statement.

IN package_spec
Identifies the package in which the referenced SQL statement resides. The package_spec must identify a package that exists at the application server.

The DESCRIBE option must have been specified on the CREATE PACKAGE statement that was used to create the package.

INTO descriptor_name
Identifies an output SQLDA structure that is to receive information about the columns that are to be retrieved by the described SQL statement. This is identical to the descriptor used for the dynamic DESCRIBE statement.

USING
This works the same as in the dynamic DESCRIBE statement, and follows the same rules. (See DESCRIBE for more information). The labels returned in the SQLDA are those which were in the SYSCOLUMNS catalog table when the SQL statement was prepared.

Examples

DESCRIBE :STMID IN :USERID.:PACKNAME INTO MYSQLDA

|DESCRIBE CURSOR

| |

|The DESCRIBE CURSOR statement obtains information about the result set that |is associated with the cursor. The information, such as column |information, is put into a descriptor. Use DESCRIBE CURSOR for result |set cursors from stored procedures. The cursor must be defined with the |ALLOCATE CURSOR statement.

|Invocation

|This statement can be embedded in an application program only. It is |an executable statement that cannot be dynamically prepared.

|Authorization

|None required.

|Syntax


|

>>-DESCRIBE CURSOR--+-cursor-name---+---INTO--descriptor-name--><
                    '-host-variable-'
 

|Description |

|cursor-name or host-variable | |
|Identifies a name for the cursor. The name specified for |cursor-name must be unique within the logical unit of work in which |it is used. It is an ordinary identifier.

|If a host-variable is specified, the following rules apply: |

|INTO descriptor-name
|Identifies an SQL descriptor area (SQLDA). The information returned |in the SQLDA describes the columns in the result set associated with the named |cursor. The considerations for allocating and initializing the SQLDA |are similar to those of a DESCRIBE statement used for describing a SELECT |statement. After executing the DESCRIBE CURSOR statement, the contents |of the SQLDA are the same as the DESCRIBE of a SELECT statement, with the |following exceptions: | |

|Notes |

  1. |For the DESCRIBE CURSOR statement to be successful, the application must |be connected to the site at which the stored procedure was executed. |

|Examples

|The statements in the following examples are assumed to be in PL/I |programs.

|Example 1

|Place information about the result set associated with cursor C1 into |the descriptor named by :sqlda1:

|   EXEC SQL DESCRIBE CURSOR C1 INTO :sqlda1

|Example 2

|Place information about the result set associated with the cursor named |by :hv1 into the descriptor named by :sqlda2:

|   EXEC SQL DESCRIBE CURSOR :hv1 INTO :sqlda2
| |

|DESCRIBE PROCEDURE

| |

|The DESCRIBE PROCEDURE statement obtains information about the result sets |returned by a stored procedure. The information, such as the number of |result sets, is put into a descriptor.

|Invocation

|This statement can be embedded in an application program only. It is |an executable statement that cannot be dynamically prepared.

|Authorization

|None required.

|Syntax


|

>>-DESCRIBE PROCEDURE--+-host-variable--+---INTO--descriptor-name-->
                       '-procedure-name-'
 
>--------------------------------------------------------------><
 

|Description |

|host-variable or procedure-name | |
|Identifies the stored procedure to describe. The procedure name may |be specified either directly or within a host-variable.

|If a host-variable is specified, it must be a character-string |variable and it must not include an indicator variable. Note that the |value is not converted to uppercase. |Procedure name must be left-justified.

|If procedure-name is specified, it must be an ordinary identifier, |which implies that it cannot contain blanks or special characters, and the |value is converted to uppercase. Therefore, if it is necessary to use a |lowercase name that contains blanks or special characters, then the name must |be specified in a host variable. The form in which a procedure name |exists varies according to the server where the procedure is stored. |

|DB2 Server for VSE & VM:
|The name of the procedure to execute. The name can be up to 18 |characters long and must match a value in the NAME column of the |SYSTEM.SYSROUTINES catalog table.

|DB2 Common Server/UDB:
|

|procedure-name
|The name (with no extension) of the procedure to execute. This is |used both as the name of the stored procedure library and the function name |within that library.

|procedure-library!function-name
|The exclamation point character acts as a delimiter between the library |name and the function name of the stored procedure.

|absolute-path!function-name
|The absolute-path specifies the complete path to the stored procedure |library. |

|In all of these cases the total length of the procedure name including its |implicit or explicit full path must not be longer than 254 bytes.

|DB2 for MVS V4 or DB2 for OS/390 V5 Server:
|An implicit or explicit three-part name. The parts are as |follows: |

|high order
|The location name of the server where the procedure is stored.

|middle
|SYSPROC

|low order
|Some value in the PROCEDURE column of the SYSIBM.SYSPROCEDURES |catalog table. |

|DB2 for OS/400 (V3.1 or later) Server:
|The external program name is assumed to be the same as the |procedure-name. For portability, the procedure-name should be specified |as a single token no larger than eight bytes. The ASSOCIATE LOCATORS |statement can only be executed against a stored procedure that has already |been invoked by the program using the SQL CALL statement. |

|INTO descriptor-name
|Identifies an SQL descriptor area (SQLDA). The information returned |in the SQLDA describes the result sets returned by the stored |procedure. Before the DESCRIBE PROCEDURE statement is processed, the |following variable in the SQLDA must be set: |

|SQLN
|Indicates the number of variables represented by SQLVAR. (SQLN acts |as a dimension of the SQLVAR array.) SQLN must be set to a value |greater than or equal to zero before the DESCRIBE PROCEDURE statement is |processed. This value should reflect the expected number of result sets |the stored procedure is to return. |

|When the DESCRIBE PROCEDURE statement is processed, the database manager |assigns values to the variables of the SQLDA as follows: |

|SQLDAID
|This field serves only as an SQLDA eye-catcher. It is set to |'SQLPR'.

|SQLD
|This field is set to the total number of result sets. A value of |zero in the field indicates there are no result sets.

|SQLVAR
|This is an array with an arbitrary number of occurrences of the variables |listed below, and others that are not mentioned. There is one SQLVAR |entry for each result set. If the value of SQLD is zero, or greater |than the value of SQLN, no values are assigned to the occurrences of |SQLVAR. If the value of SQLD is n, where n is |greater than zero but less than or equal to the value of SQLN, values are |assigned to the first n occurrences of SQLVAR. Therefore, |the first occurrence of SQLVAR contains a description of the first result set, |the second occurrence of SQLVAR contains a description of the second result |set, and so on. |

|SQLDATA
|This field of each SQLVAR entry is set to the result set locator value |associated with the result set.

|SQLIND
|This field of each SQLVAR entry is set to the estimated number of rows in |the result set.

|SQLNAME
|This field is set to the name of the cursor used by the stored procedure |to return the result set. |
|
|

|Notes |

  1. |A value of |-1 in the SQLIND field indicates that an estimated number of rows in |the result set is not provided.
  2. |DESCRIBE PROCEDURE does not return information about the parameters |expected by the stored procedure. |

|Examples

|The statements in the following examples are assumed to be in PL/I |programs.

|Example 1

|Place information about the result sets returned by stored procedure P1 |into the descriptor named by :sqlda1:

|   EXEC SQL DESCRIBE PROCEDURE P1 INTO :sqlda1

|Example 2

|Place information about the result sets returned by stored procedure |named by :hv1 into the descriptor named by :sqlda2:

|   EXEC SQL DESCRIBE PROCEDURE :hv1 INTO :sqlda2
| |

DROP

The DROP statement deletes an object. Any objects that are directly or indirectly dependent on that object are also deleted. Whenever an object is deleted, its description is deleted from the catalog and any packages that reference the object are invalidated.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

Syntax



>>-DROP----+-DBSPACE--dbspace_name-------+---------------------><
           +-INDEX--index_name-----------+
           |         (1)                 |
           +-PACKAGE-------package_spec--+
           +-SYNONYM--synonym------------+
           +-TABLE--table_name-----------+
           '-VIEW--view_name-------------'
 


Notes:



  1. PROGRAM is equivalent to PACKAGE and is provided for compatibility with
    older versions of SQL/DS.


Description

DBSPACE dbspace_name
Identifies the dbspace to be dropped. It must be a dbspace that exists at the application server. Dropping a dbspace destroys the contents of a dbspace. When the logical unit of work is committed, the dbspace is available to be acquired. All existing packages with dependencies on tables within the dropped dbspace are automatically marked unusable. Both private and public dbspaces can be dropped, but only someone with DBA authority can drop a public dbspace. No user, even with DBA authority, can drop the dbspace containing the database manager catalogs.

INDEX index_name
Identifies the index to be dropped. It must be an index that exists at the application server. The table on which the index is defined is not affected. All existing packages that use the dropped index are marked unusable.

An index created by a primary key cannot be dropped.

PACKAGE package_spec
Identifies the package to be dropped. It must be a package that exists at the application server. Once a package is dropped, the program that uses that package cannot be run. An owner can only drop packages that that owner has preprocessed. Only someone with DBA authority can drop another user's package.

DROP PACKAGE cannot support a qualified host structure subfield name in the package_spec. A host structure subfield name may be used here as a normal host_variable but must be unqualified. If being unqualified results in an ambiguous reference, the subfield identifier name cannot be used with DROP PACKAGE.

If the package was created using a host identifier which was not an ordinary identifier (such as a package name beginning with a number), it must be dropped using a host identifier; otherwise an SQL error will result. For example, if a package named 071PACK was created using a host identifier and a

  DROP PACKAGE 071PACK

statement is issued, an SQLCODE of -105 (SQLSTATE of 37501) will result.

SYNONYM synonym
Identifies a synonym to be dropped. In a static DROP SYNONYM statement, the name must identify a synonym that is owned by the owner of the package. In a dynamic DROP SYNONYM statement, the name must identify a synonym that is owned by the authorization ID that is executing the statement.

Dropping a synonym has no effect on the table or view that it references. Dropping a synonym does not affect the packages of existing programs that use the synonym, because in the packages the synonym has already been resolved to a real table name. However, a program containing a dropped synonym cannot be preprocessed successfully, either automatically or by user request.

TABLE table_name
Identifies a table to be dropped. It must be a base table that exists at the application server and cannot be a catalog table. The table is deleted from the database and the contents of the table are lost. All indexes, keys, constraints, and views defined on the table, and all privileges granted on the table, are also dropped. Synonyms are not dropped. No user, even with DBA authority, can drop a table which forms part of the database manager system catalog.

All existing packages affected by dropping the table are marked unusable. The unusable packages remain in the database until they are explicitly dropped by a DROP PACKAGE statement. When an SQL statement attempts to invoke an unusable package, the database manager tries to dynamically rebind the package. However, if the SQL statement refers to a dropped DBSPACE or table, that SQL statement returns an error code at execution time.

VIEW view_name
Identifies the view to be dropped. It must be a view that exists at the application server. The definition of the view is deleted from the catalog. The definition of any view that is directly or indirectly dependent on that view is also deleted. Whenever the definition of a view is deleted from the catalog, all privileges on that view are also deleted.

All existing packages that use the dropped view are marked unusable.

Notes

If a DROP statement is issued for an object while some program that depends on the object is running and has a logical unit of work in progress, the DROP statement does not take effect until the end of the running logical unit of work. Meanwhile, the program that has issued the DROP waits.

When dropping a table, the database manager temporarily requires additional space so it can restore the table in case the logical unit of work is not committed. The database manager behaves as though a table approximately doubles in size immediately before it is dropped. The empty pages are taken from the DBSPACE from which the table was dropped. If the number of empty pages is less than approximately double the table size, the database manager will stop processing and will not issue a ROLLBACK. Note that if all rows of a table have previously been deleted, such additional space is not required.

Examples

Example 1

Drop your table named MY_IN_TRAY.

  DROP TABLE MY_IN_TRAY

Example 2

Drop your view named MA_PROJ.

  DROP VIEW MA_PROJ

Example 3

Drop the package named PACKA.

  DROP PACKAGE PACKA

Example 4

Drop the dbspace named MYSPACE that is owned by MIKE. (Note that the authorization id submitting this statement must have DBA authority.)

  DROP DBSPACE MIKE.MYSPACE

DROP PROCEDURE

The DROP PROCEDURE statement removes the definition of a stored procedure from the database manager, and takes the information for that procedure out of the cache.

The STOP PROC command must be issued with the REJECT option before the DROP PROCEDURE statement will be accepted.

Invocation

This statement can be issued from an application program or interactively. It is an executable statement that can be dynamically prepared.

Authorization

The issuer of the DROP PROCEDURE statement must have DBA authority.

Syntax



>>-DROP PROCEDURE---procedure-name----+-----------------+------->
                                      '-AUTHID--authid--'
 
>-----+----------+---------------------------------------------><
      '-RESTRICT-'
 

Description

procedure-name
must identify a stored procedure that has been defined (that is, a CREATE PROCEDURE has been processed for it).

Note that DROP PROCEDURE removes the definition of the procedure only; the package associated with the procedure, as well as the load module or phase, is untouched.

authid
The authorization ID for the stored procedure. If specified, then only the version of procedure-name that is accessible only by authid will be dropped.

RESTRICT
This is included for compatibility with the DB2 family. If specified, it is ignored.

Examples

Example 1
   DROP PROCEDURE MYPROC

DROP PSERVER

The DROP PSERVER statement removes the definition of a stored procedure server from the database manager, and takes the information for that server out of the cache.

The STOP PSERVER command must be issued with the NOIMPLICIT option before the DROP PSERVER statement will be accepted.

A stored procedure server cannot be dropped if the following are all true:

Note:If the drop fails for this reason, issue the ALTER PROCEDURE statement and use the SERVER GROUP clause to indicate that the procedure is to be moved to a different group, then issue the DROP PSERVER statement again.

Invocation

This statement can be issued from an application program or interactively. It is an executable statement that can be dynamically prepared.

Authorization

The issuer of the DROP PSERVER statement must have DBA authority.

Syntax



>>-DROP PSERVER---procedure-server-----------------------------><
 

Description

procedure-server
The name of the stored procedure server. This name must be an ordinary identifier of 1 to 8 characters.

Examples

Example 1

   DROP PSERVER SRV1

DROP STATEMENT

The DROP STATEMENT statement selectively deletes a statement from a package. DROP STATEMENT applies only to packages created with a CREATE PACKAGE statement with the MODIFY option.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the statement must have one of the following:

Syntax



>>-DROP STATEMENT--section_variable--IN--package_spec----------><
 

Description

section_variable
Identifies the statement defined by an Extended PREPARE statement.

IN package_spec
Identifies the package in which the referenced SQL statement resides. The package_spec must identify a package that exists at the application server.

Notes

When a statement references an incorrect package, dynamic re-preprocessing will occur to restore the package to a usable state. If the package has any unresolved dependencies, the re-processing will fail and a message will be issued.

Examples

DROP STATEMENT :STMID IN :USERID.:PACKNAME

END DECLARE SECTION

The END DECLARE SECTION statement marks the end of a host variable declare section.

Invocation

This statement can only be embedded in an application program. It is not an executable statement. It is not supported in REXX.

Authorization

None required.

Syntax



>>-END DECLARE SECTION-----------------------------------------><
 

Description

See BEGIN DECLARE SECTION for a description of the END DECLARE SECTION statement.

Example

See BEGIN DECLARE SECTION for examples using the END DECLARE SECTION statement.

EXECUTE

The EXECUTE statement processes a prepared SQL statement.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared.

Authorization

See PREPARE for the authorization required to create a prepared statement.

Syntax



>>-EXECUTE--statement_name-------------------------------------->
 
>-----+------------------------------------+-------------------><
      +-USING----host_variable_list--------+
      '-USING DESCRIPTOR--descriptor_name--'
 

Description

statement_name
Is an ordinary identifier that identifies the prepared statement to be processed. Statement_name must identify a statement that was previously prepared within the logical unit of work and the prepared statement must not be a SELECT statement.

USING
Introduces a list of host variables, host structures, or both, whose values are substituted for the parameter markers (question marks) in the prepared statement. (For an explanation of parameter markers, see PREPARE.) If the prepared statement includes parameter markers, the USING clause must be used. USING is ignored if there are no parameter markers.

host_variable_list
Identifies one or more host variable, host structure, or both that must be declared in the program in accordance with the rules for declaring host variables and host structures.

The total number of host variables and host structure subfields must be the same as the number of parameter markers in the prepared statement. The nth variable or subfield corresponds to the nth parameter marker in the prepared statement.

DESCRIPTOR descriptor_name
Identifies an input SQLDA structure that provides information concerning input variables that were specified as parameter markers (?) when the statement was prepared.

Before the EXECUTE statement is processed, the user must set the following fields in the SQLDA:

  • SQLN to indicate the number of SQLVAR occurrences provided in the SQLDA
  • SQLDABC to indicate the number of bytes of storage allocated for the SQLDA
  • SQLD to indicate the number of variables used in the SQLDA when processing the statement
  • SQLVAR occurrences to indicate the attributes of the variables and the addresses of the data areas allowed to contain the result.

The SQLDA must have enough storage to contain all SQLVAR occurrences. Therefore, the value in SQLDABC must be greater than or equal to 16 + SQLN*(44).

SQLD must be set to a value greater than or equal to zero and less than or equal to SQLN. It must be the same as the number of parameter markers in the prepared statement. The nth variable described by the SQLDA corresponds to the nth parameter marker in the prepared statement. (For a description of an SQLDA, see SQL Descriptor Area (SQLDA).)

Parameter Marker Replacement

Before the prepared statement is processed, each parameter marker in the statement is effectively replaced by its corresponding host variable or host structure subfield. The replacement is an assignment operation in which the source is the value of the host variable or host structure subfield and the target is a variable within the database manager. The assignment rules are those described for assignment to a column in Assignments and Comparisons. The attributes of the target variable depend on the role that the parameter marker plays in its SQL statement. The rules for the various roles are shown below. In those rules, "P" represents the parameter marker in question.

Arithmetic Operand

When P is an operand for an infix operator, the other operand cannot also be a parameter marker. The data type, scale, and precision of the target for P are the same as those of the other operand. When P is the operand of unary minus, the data type of the target is double precision floating point.

The Pattern in a LIKE Predicate  With P in this role, the target is a varying length string.

Comparand  In this case, P can be a comparand in a basic predicate (for example, "?>10"), in an IN predicate, or in a BETWEEN predicate. At least one of the comparands in such a predicate must not be a parameter marker.

For a basic predicate, the other comparand cannot be a parameter marker.

When the parameter marker is specified as a comparison operand in the BETWEEN predicate,

When the parameter marker is specified as a comparison operand in the IN predicate,

The attributes of the target for P are the same as those of the other comparand in the predicate, unless the data type of that comparand is DATE, TIME, or TIMESTAMP, in which case the target is effectively CHAR(254).

Assignment Operand  For this case, P must be the value for a column in an INSERT or UPDATE. The attributes of the target are the same as those of the column, with the following exceptions:

If the column has the data type DATE, TIME, or TIMESTAMP, trailing blanks are removed from the resulting string before assignment to the target. This is the one exception to the rule that the target is treated like a column.

General Rules  Let V denote a host variable that corresponds to a parameter marker P. The value of V is assigned to the target variable for P in accordance with the rules for assigning a value to a column:

When the prepared statement is processed, the value used in place of P is the value of the target variable V. For example, if V is CHAR(6) and the target is CHAR(8), the value used in place of P is the value of V padded on the right with two blanks.

Examples

This example of portions of a COBOL program shows how an INSERT statement with parameter markers is prepared and processed.

  EXEC SQL  BEGIN DECLARE SECTION  END-EXEC.
    77 EMP              PIC X(6).
    01 PROJECT.
       05 PRJ              PIC X(6).
       05 ACT              PIC S9(4) COMP-4.
       05 TIM              PIC S9(3)V9(2).
    01 HOLDER.
       49  HOLDER-LENGTH    PIC S9(4) COMP-4.
       49  HOLDER-VALUE     PIC X(80).
  EXEC SQL  END DECLARE SECTION  END-EXEC.
    .
    .
    .
  MOVE 70 TO HOLDER-LENGTH.
  MOVE "INSERT INTO EMP_ACT (EMPNO, PROJNO, ACTNO, EMPTIME)
-              VALUES (?, ?, ?, ?)" TO HOLDER.
  EXEC SQL  PREPARE MYINSERT FROM :HOLDER  END-EXEC.
 
  IF SQLCODE = 0
    PERFORM DO-INSERT THRU END-DO-INSERT
  ELSE
    PERFORM ERROR-CONDITION.
 
  DO-INSERT.
    MOVE "000010" TO EMP.
    MOVE "AD3100" TO PRJ.
    MOVE 160      TO ACT.
    MOVE .50      TO TIM.
    EXEC SQL  EXECUTE MYINSERT USING :EMP, :PROJECT END-EXEC.
  END-DO-INSERT.
    .
    .
    .

Extended EXECUTE

The Extended EXECUTE statement processes an SQL statement that was prepared previously using an Extended PREPARE statement.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the statement must have one of the following:

Syntax



>>-EXECUTE--section_variable--IN--package_spec------------------>
 
>-----+-------------------------------------+------------------->
      '-USING DESCRIPTOR--descriptor_name1--'
 
>-----+--------------------------------------------+-----------><
      '-USING OUTPUT DESCRIPTOR--descriptor_name2--'
 

Description

section_variable
Identifies a statement defined by an Extended PREPARE statement. The Extended EXECUTE statement does not have to be in the same logical unit of work or program as the Extended PREPARE statement that was originally used to process the statement.

IN package_spec
Identifies the package in which the referenced SQL statement resides. The package_spec must identify a package that exists at the application server.

USING DESCRIPTOR descriptor_name1
Identifies an input SQLDA structure that provides information concerning input variables that were specified as parameter markers (?) when the statement was prepared.

USING OUTPUT DESCRIPTOR descriptor_name2
Identifies an output SQLDA structure that provides information about variables into which individual fields are to be returned by the query.

This clause is only valid when using the EXECUTE statement against a section created by the PREPARE SINGLE ROW statement and in such cases the clause is required.

Before the Extended EXECUTE statement is processed, the user must set the fields in the SQLDA described in the "Description" section of EXECUTE and Table 20.

Notes

When the statement is processed, the host variables specified in the SQLDA are substituted, in order, into the statement in place of the parameter markers (?) that were given in the Extended PREPARE statement. Each variable must be of a data type that is compatible with its usage in the "prepared" SQL statement. Extended EXECUTE will fail if the prepared statement was a select-statement (in this case, an Extended DECLARE CURSOR coupled with an Extended OPEN, FETCH, and CLOSE should be used).

Examples

 EXECUTE :STMID IN :USERID.:PACKNAME
   USING DESCRIPTOR INSQLDA
   USING OUTPUT DESCRIPTOR OUTSQLDA

EXECUTE IMMEDIATE

The EXECUTE IMMEDIATE statement:

EXECUTE IMMEDIATE combines the basic functions of the PREPARE and EXECUTE statements. It may be used to prepare and process SQL statements that contain neither host variables nor parameter markers.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared.

Authorization

The authorization rules are those defined for the SQL statement specified by EXECUTE IMMEDIATE. For example, see INSERT Rules for the authorization rules that apply when an INSERT statement is processed using EXECUTE IMMEDIATE. The authorization ID is the run-time authorization ID.

Syntax



>>-EXECUTE IMMEDIATE----+-string_constant-+--------------------><
                        '-host_variable---'
 

Description

string_constant
String constants are supported in all languages except Assembler and C.

It is advisable to avoid using either delimited identifiers or DBCS strings in statements specified in string constants.

host_variable

Identifies a host variable that must be described in the program in accordance with the rules for declaring host variables. An indicator variable must not be specified.

In Assembler, C, COBOL, REXX, the host variable must be a varying-length string variable. In C, it cannot be a NUL-terminated string. In FORTRAN, the host_variable must be a fixed-length string variable. In PL/I, the host variable can either be a fixed-length or varying-length string variable. The host variable must have a maximum length of 8192.

See PREPARE for more information on the use of DBCS constants in prepared statements in PL/I Version 2 programs.

The string_constant or host_variable must contain one of the following SQL statements:

 
ACQUIRE DBSPACE
ALTER DBSPACE
ALTER PROCEDURE
ALTER PSERVER
ALTER TABLE
COMMENT ON
CREATE INDEX
CREATE PROCEDURE
CREATE PSERVER
CREATE SYNONYM
CREATE TABLE
CREATE VIEW
DELETE
DROP
DROP PROCEDURE
DROP PSERVER
EXPLAIN
GRANT Package Privileges
GRANT System Authorities
GRANT Table/View Privileges
INSERT
LABEL ON
LOCK DBSPACE
LOCK TABLE
REVOKE Package Privileges
REVOKE System Authorities
REVOKE Table/View Privileges
UPDATE
UPDATE STATISTICS

Furthermore, the statement string must not:

Notes

When an EXECUTE IMMEDIATE statement is processed, the specified statement string is parsed and checked for errors. If the SQL statement is incorrect it is not processed and the error condition that prevents its execution is reported in the SQLCA. If the SQL statement is valid, but an error occurs during its execution, that error condition is reported in the SQLCA.

If the same SQL statement is to be processed more than once, it is more efficient to use the PREPARE and EXECUTE statements rather than the EXECUTE IMMEDIATE statement.

Examples

Use PL/I program statements to move an SQL statement to the host variable QSTRING (char(80)) and prepare and process whatever SQL statement is in the host variable QSTRING.

  IF ACCOUNTS = 'BIG' THEN
   QSTRING = 'INSERT INTO WORK_TABLE SELECT * FROM EMP_ACT WHERE    ACTNO <100';
  ELSE
   QSTRING = 'INSERT INTO WORK_TABLE SELECT * FROM EMP_ACT WHERE    ACTNO >=100';
   .
   .
   .
  EXEC SQL  EXECUTE IMMEDIATE :QSTRING;

EXPLAIN

The EXPLAIN statement places information about the structure and execution performance for a DELETE, INSERT, UPDATE, or SELECT statement into one or more user-supplied tables.

The information applies to the statement for which the EXPLAIN was issued, and for any statements that have been generated internally by the database manager. Internal statements are generated to ensure referential integrity.

The result tables used by the EXPLAIN statement are updated during preprocessing of the containing program.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include both:

Syntax



>>-EXPLAIN----+-ALL-----------------+--------------------------->
              |  .-,--------------. |
              |  V                | |
              '----+-COST------+--+-'
                   +-PLAN------+
                   +-REFERENCE-+
                   '-STRUCTURE-'
 
>-----+-------------------------+------------------------------->
      '-SET QUERYNO =--integer--'
 
>----FOR--explainable_sql_statement----------------------------><
 

Description

COST
Inserts into the COST_TABLE the complete cost of the command being analyzed and for any statements internally generated by the database manager to enforce referential integrity.

PLAN
Inserts information into the PLAN_TABLE about the order in which tables are accessed during execution of the statement being analyzed and for any internally generated statements used to enforce referential integrity. Also describes the indexes used to access the tables, the methods that the database manageruses to do joins, and the sorts done as part of processing.

REFERENCE
Inserts one row into the REFERENCE_TABLE for each column referenced in the statement and for any statements internally generated by the database managerto enforce referential integrity.

STRUCTURE
Inserts one row into the STRUCTURE_TABLE for each query block in the statement.

ALL
Inserts information into all four of the above tables.

SET QUERYNO=integer
An integer constant that can fit into an INTEGER field. The SET QUERYNO clause lets you place an integer value into the QUERYNO fields of the rows in the explanation tables. Assigning a different number on each EXPLAIN will make it easier to identify information collected. The integer value must not be preceded by a sign and may range from 1 to 2147483647.

The SET QUERYNO clause is optional. If you omit it, a null value is placed in the fields of the rows inserted by the EXPLAIN statement.

FOR explainable_sql_statement
The SQL statement to be analyzed. You can analyze UPDATE, DELETE, and INSERT statements as well as SELECT statements. (SELECT statements are considered the primary candidates for EXPLAIN analysis.) explainable_sql_statement is not a quoted-string and must not be put in a host variable. Host variables may not be placed in the statement; rather parameter markers must be used and the entire EXPLAIN statement must be dynamically prepared and processed.

The length of the SQL statement is limited to 8192 characters.

The database manager supplies customizable macros to build a set of EXPLAIN tables for each authorization ID that needs it. For IBM VM systems, the macro file is ARISEXP MACRO; for VSE systems, the macro is an A-type member, ARISEXP. Both macros contain comments describing the required customizing procedure.

EXPLAIN may be invoked either explicitly as an SQL statement or implicitly with the EXPLAIN(YES) option for CREATE PACKAGE and application program preprocessing. The following tables describe the columns required in each table associated with EXPLAIN. |For more information about interpreting the data in these tables, |see the DB2 Server for VSE & VM Performance Tuning Handbook, GC09-2987.

Table 10. Columns in COST_TABLE
Column Name Data Type Description
QUERYNO INTEGER

Query number is intended to distinguish among queries. QUERYNO is set to the value specified in the SET QUERYNO clause. If the clause is omitted, QUERYNO is set to NULL.

For an entry generated by the EXPLAIN(YES) option during program preprocessing, QUERYNO corresponds to the section number in the package for the statement being explained.

RINO SMALLINT NOT NULL

RINO is set to zero for the user's original statement and will be automatically incremented by one for each internally-generated statement that is processed for referential integrity or cascade delete. RINO is intended to distinguish among queries and internally-generated queries. If RINO reaches 32,767, the next internally-generated statement will have a corresponding RINO value of 1, and so on.

QBLOCKNO SMALLINT NOT NULL

Query block number, where 1 is the outer-level query block. Different query blocks (as occur in subqueries) receive different numbers.

PKGNAME CHAR(8) NOT NULL This identifies the name of the package in which this SQL statement originated. This field is blank for explicit EXPLAIN processing invoked by the EXPLAIN statement.
PKGOWNER CHAR(8) NOT NULL This identifies the owner of the package in which this SQL statement originated. This field is blank for explicit EXPLAIN processing invoked by the EXPLAIN statement.
COST FLOAT NOT NULL

When QBLOCKNO is 1, this is a floating point number that represents the total estimated cost of executing the statement for which the EXPLAIN is issued and for any statement internally generated by the database managerto enforce referential integrity. For other values of QBLOCKNO, this is the cost of the subquery that has this query block as its root (as opposed to the cost of the query block alone). To find the cost of the query block alone, use information from the STRUCTURE_TABLE. The technique for doing this is described in the DB2 Server for VSE & VM Database Administration manual.

TIMESTAMP TIMESTAMP NOT NULL The time at which the EXPLAIN statement was processed.


Table 11. Columns in PLAN_TABLE
Column Name Data Type Description
QUERYNO INTEGER

Query number is intended to distinguish among queries. (See COST_TABLE for a description of QUERYNO.)

RINO SMALLINT NOT NULL

RINO is intended to distinguish among queries and internally-generated queries. (See COST_TABLE for a description of RINO.)

QBLOCKNO SMALLINT NOT NULL

Query block number, where 1 is the outer level query block (which may have subqueries). Different query blocks receive different numbers. The plans for executing different query blocks do not refer to each other. However, STRUCTURE_TABLE provides the parent block for each query block, and indicates when the query block is done. This information is always implicitly part of the execution plan.

PKGNAME CHAR(8) NOT NULL This identifies the name of the package in which this SQL statement originated. This field is blank for explicit EXPLAIN processing invoked by the EXPLAIN statement.
PKGOWNER CHAR(8) NOT NULL This identifies the owner of the package in which this SQL statement originated. This field is blank for explicit EXPLAIN processing invoked by the EXPLAIN statement.
PLANNO SMALLINT NOT NULL

A number identifying the current step of the plan. PLANNO indicates the order in which the database managerdoes the actions of the plan for processing the query block. The PLAN_TABLE row with PLANNO 1 indicates the first action, PLANNO 2 indicates the second action, and so on. For each query block, each row entered as the result of an execution of EXPLAIN PLAN has a different PLANNO value.

METHOD SMALLINT NOT NULL

METHOD is the action done at this step; it is either 0, 1, 2 or 3.

Method is 0 only for the first table accessed (which has PLANNO 1). Because this is the first table, there is not yet a composite. Also, because there is no composite, SORTCOMP (described below) is blank for this row.

Methods 1 and 2 correspond to plan steps that are joins, and identify the method by which the join is performed. Method 1 is the nested loop join. That is, for each row of the composite, the database managerfinds and joins matching rows of the new table. Method 2 is the merge scan join. In a merge scan join, the database managerscans the composite and the new table in order according to the join column. It then joins rows with matching join columns. This resembles processes used in merging files, except that one row in the composite may match many rows of the new table, and many rows in the composite may match one row of the new table.

Method 3 indicates that the database managermust perform additional sorts at the end of processing the query block. The following sorts are possible:

ORDER BY
GROUP BY
SELECT DISTINCT
UNION.

When METHOD is 3, CREATOR is all blanks, TNAME is the empty string, TABNO is zero, and SORTNEW is N.

CREATOR CHAR(8) NOT NULL

Creator of the new table accessed in this plan step.

TNAME VARCHAR(18) NOT NULL

Name of the new table accessed in the plan step.

TABNO SMALLINT NOT NULL

Because a table may be joined to itself, there may be several references to the same table in a query block. TABNO distinguishes the different references. TABNO, CREATOR, and TNAME correspond to the columns with the same names in REFERENCE_TABLE. When there is no new table then these columns have the values specified when METHOD is 3 (see above).

ACCESSTYPE CHAR(2) NOT NULL

Indicates how the database manager will access the data. These are the character values that can appear in ACCESSTYPE:

I1
Accesses the new table by a fetch operation on a fully-qualified unique index. This includes fetching the first or last value of the index.
I
Accesses the new table using an index and specific key values (identified in ACCESSCREATOR and ACCESSNAME).
N
Accesses the new table using an index on the column in an IN predicate with a list of literals.
W
Accesses the new table using an index, but without specific key values. This non-selective index scan locates the rows in a table when it is more efficient to scan the index than to scan all pages in the DBSPACE.
R
Accesses the new table by a scan of the DBSPACE in which it resides.
L
Accesses the new table through the internal list. The internal list is like a temporary table. It is created to contain the result of a materialized view.

For any type of index access, ACCESSCREATOR and ACCESSNAME identify the index. ACCESSTYPE is blank for the top block of INSERT statements, as well as for UPDATE and DELETE statements that use WHERE CURRENT OF CURSOR clauses. ACCESSCREATOR is blanks and ACCESSNAME is the null value in that case. (Access for INSERT's is performed using the first index created; UPDATE and DELETE statements using the CURRENT OF CURSOR clause access using their cursors.)

MATCHCOLS SMALLINT NOT NULL For ACCESSTYPE 'I1', 'I', or 'N', the number of index keys that have key-matching predicates used in an index scan; otherwise, 0.
ACCESSCREATOR CHAR(8) NOT NULL

For ACCESSTYPE 'I1', 'I', 'N', or 'W', ACCESSCREATOR contains the owner of the access path (index) that the database manageruses to access the table. Otherwise, ACCESSCREATOR contains blanks.

ACCESSNAME VARCHAR(18) NOT NULL

For ACCESSTYPE 'I1', 'I', 'N', or 'W', ACCESSNAME contains the name of the access path (index) that the database manageruses to access the table. Otherwise, ACCESSNAME contains blanks.

INDEXONLY CHAR(1) NOT NULL Indicates whether an index is sufficient to satisfy the request, and to what degree.
Y
All predicates may be applied to the index pages and all data may be retrieved from the index pages.
W
All sargable predicates may be applied to the index pages, but data pages must be accessed to retrieve data satisfying the predicates or residual predicates.
N
Data pages must be accessed to resolve predicates and retrieve data. Note that, in a few circumstances, some predicate filtering may still be achieved using an index.
SORTNEW CHAR(1) NOT NULL

To access a table in a particular order, the database manager may sort some fields of some rows of the new table (for example, for merge scan joins). These are the character values that can appear in SORTNEW:

N
If the database manager does not sort the new table.
U
If the database manager does sort, and removes duplicates.
Y
If the database manager sorts, and does not remove duplicates.

SORTNEW is blank when no sort of the new table is possible, that is, when METHOD is 3 and there is no new table.

SORTCOMP CHAR(1) NOT NULL

To access a composite in a particular order, the database manager may sort some fields of some rows of the composite. These are the character values that can appear in SORTCOMP:

N
If the database manager does not sort the composite.
U
If the database manager does sort, and removes duplicates.
Y
If the database manager does sort, and does not remove duplicates.

SORTCOMP is blank when no sort of the composite is possible; that is, when METHOD is 0 and there is no composite yet.

SORTN_UNIQ CHAR(1) NOT NULL Whether a sort is performed on the new table to remove duplicate rows. Y = Yes; N = No.
SORTN_JOIN CHAR(1) NOT NULL Whether a sort is performed on the new table if METHOD is 2. Y = Yes; N = No.
SORTN_ORDERBY CHAR(1) NOT NULL Whether an ORDER BY clause results in a sort on the new table. Y = Yes; N = No.
SORTN_GROUPBY CHAR(1) NOT NULL Whether a GROUP BY clause results in a sort on the new table. Y = Yes; N = No.
SORTC_UNIQ CHAR(1) NOT NULL Whether a sort is performed on the composite table to remove duplicate rows. Y = Yes; N = No.
SORTC_JOIN CHAR(1) NOT NULL Whether a sort is performed on the composite table if METHOD is 2. Y = Yes; N = No.
SORTC_ORDERBY CHAR(1) NOT NULL Whether an ORDER BY clause results in a sort on the composite table. Y = Yes; N = No.
SORTC_GROUPBY CHAR(1) NOT NULL Whether a GROUP BY clause results in a sort on the composite table. Y = Yes; N = No.
TIMESTAMP TIMESTAMP NOT NULL The time at which the EXPLAIN statement was processed.
REMARKS VARCHAR(254) NOT NULL A field into which you can insert any character string of 254 or fewer characters.


Table 12. Columns in REFERENCE_TABLE
Column Name Data Type Description
QUERYNO INTEGER

Query number. QUERYNO is intended for your use to distinguish among queries. (See COST_TABLE for a description of QUERYNO.)

RINO SMALLINT NOT NULL RINO is intended to distinguish among queries and internally generated queries. (See COST_TABLE for a description of RINO.)
QBLOCKNO SMALLINT NOT NULL

Query block number, where 1 is the top level query block, that may have subqueries. Different query blocks receive different numbers.

PKGNAME CHAR(8) NOT NULL This identifies the name of the package in which this SQL statement originated. This field is blank for explicit EXPLAIN processing invoked by the EXPLAIN statement.
PKGOWNER CHAR(8) NOT NULL This identifies the owner of the package in which this SQL statement originated. This field is blank for explicit EXPLAIN processing invoked by the EXPLAIN statement.
REFTYPE CHAR(6) NOT NULL An indication of the purpose of the current row in this table. Rows are inserted for three reasons:
  1. For each SQL statement, REFTYPE has a value indicating the type of statement:

    SELECT
    A select statement

    INSERT
    An insert statement

    UPDATE
    An update statement

    DELETE
    A delete statement

    SELUPD
    A select statement with a 'FOR UPDATE' clause

    DELCUR
    A delete where current of cursor statement

    UPDCUR
    An update where current of cursor statement
  2. For each table referenced, REFTYPE has the value 'TABLE'.
  3. For each column referenced, REFTYPE has the value 'COLUMN'.
CREATOR CHAR(8) NOT NULL

Creator of a table referenced in the query block.

TNAME VARCHAR(18) NOT NULL

Name of the table referenced in the query block.

TABNO SMALLINT NOT NULL

Because there may be several references to the same table in a query block (because a table may be joined to itself), TABNO differentiates among the different references. TABNO may correspond to the order of tables in the FROM clause of the query.

CNAME VARCHAR(18) NOT NULL Name of the column.
COLNO SMALLINT NOT NULL

Column number of a column in the table identified by CREATOR, TNAME, and TABNO. EXPLAIN REFERENCE causes at most one new row to be entered in REFERENCE_TABLE for a particular column (COLNO) of a table (TABNO) in a query block (QBLOCKNO).

FILTER FLOAT NOT NULL

The filter factor associated with the query block's most selective predicate on this column.

The selectivity of a predicate is the fraction of the rows of the column's table that is estimated to satisfy the predicate. Not all columns referenced in a statement have filter factors, however.

For each reference to a column, the EXPLAIN statement determines a filter factor if the reference to the column meets these qualifications:

  1. The column must be in a predicate that is connected by the AND logical operator to the rest of the WHERE clause. If the predicate is not connected by AND, it must have the only predicate in the WHERE clause.
  2. The predicate in which the column appears must have the form "column op expression."

For each such column reference, the EXPLAIN statement determines a "filter factor." The smallest of these filter factors is returned in FILTER. This value is between 0.0 and 1.0, and will be 1.0 if there are no predicates with filter factors for the column. Filter factor may be used to estimate the cost of modifying rows and indexes. Also, a small filter factor is one indicator that an index on the column might be useful for processing the statement.

DBSSPRED CHAR(1) NOT NULL Is there a sargable predicate (predicate applied at the first stage) associated with this column?

Y
There is a sargable predicate associated with this column. However, this sargable predicate may not necessarily be the most selective one.

N
There may be no sargable predicate associated with this column.

For each reference to a column, the EXPLAIN statement determines sargability if the reference to the column meets these qualifications:

  1. The column must be in a predicate that is connected by the AND logical operator to the rest of the WHERE clause. If the predicate is not connected by AND, it must have the only predicate in the WHERE clause.
  2. The predicate in which the column appears must have the form "column op expression."

For each such column reference, the EXPLAIN statement determines the sargability of the predicate associated with the column. If a sargable predicate exists, the value is set to 'Y'; otherwise, it is set to 'N'.

JOINPRED CHAR(1) NOT NULL Is there a sargable equi-join predicate (using equal value in tables to join) associated with this column? Y = Yes; N = No.

If yes, then DBSSPRED must be Y as well.

ORDERCOL SMALLINT NOT NULL If this column is referenced in an ORDER BY clause, give its relative position in the ORDER BY clause and sort direction. If the column is not referenced in the ORDER BY clause, ORDERCOL is zero. Sort direction is indicated by a positive number for ascending order and a negative number for descending order.
GROUPCOL SMALLINT NOT NULL If this column is referenced in a GROUP BY clause, give its relative position in the GROUP BY clause. If the column is not referenced in the GROUP BY clause, GROUPCOL is zero.
UPDATECOL CHAR(1) NOT NULL If this column is in the SET clause of an UPDATE statement, indicate how it is updated.

L
Updated by a literal.

X
Updated by a column or expression.

blank
Column is not referenced in the SET clause
TIMESTAMP TIMESTAMP NOT NULL The time at which the EXPLAIN statement was processed.

Table 13. Columns in STRUCTURE_TABLE
Column Name Data Type Description
QUERYNO INTEGER

Query number. QUERYNO is intended to distinguish among queries. (See COST_TABLE for a description of QUERYNO.)

RINO SMALLINT NOT NULL RINO is intended to distinguish among queries and internally generated queries. (See COST_TABLE for a description of RINO.)
QBLOCKNO SMALLINT NOT NULL

Query block number, where 1 is the top level query block that may have subqueries. Different query blocks will receive different numbers.

PKGNAME CHAR(8) NOT NULL This identifies the name of the package in which this SQL statement originated. This field is blank for explicit EXPLAIN processing invoked by the EXPLAIN statement.
PKGOWNER CHAR(8) NOT NULL This identifies the owner of the package in which this SQL statement originated. This field is blank for explicit EXPLAIN processing invoked by the EXPLAIN statement.
ROWCOUNT INTEGER NOT NULL

Estimated number of rows returned for the query or subquery corresponding to this query block. For queries, this is the estimated size of the response. For update and delete statements, this is the estimated number of affected rows. ROWCOUNT can be used in estimating update costs. For insert statements, the ROWCOUNT for the top level query block (QBLOCKNO 1) is always 0, but the ROWCOUNT's for other query blocks, if any, are normal estimates. ROWCOUNT is also 0 for UPDATE and DELETE statements that use WHERE CURRENT OF CURSOR clauses.

TIMES FLOAT NOT NULL

Estimated number of times that "dependent" query blocks of this block will be processed for each execution of this query block. This field is no longer in use, but is retained to provide for compatibility with older versions of the SQL/DS product.

PARENT SMALLINT NOT NULL

The query block for which this block is performed. This may be the query block in whose WHERE clause the current query block appears. However, some query blocks can be processed earlier, at the opening of a "parent" query block, because there are no correlations to intermediate query blocks tables. In this case, PARENT identifies that ancestor, rather than the parent given by the statement's structure.

ATOPEN CHAR (1) NOT NULL

These are the characters that can appear in ATOPEN:

Y
If the query is done once at each open (new invocation) of the PARENT.
N
If the number of times that the current query block is invoked (per invocation of its parent) equals the TIMES field value of the parent.

TIMESTAMP TIMESTAMP NOT NULL The time at which the EXPLAIN statement was processed.

Examples

Place information about a SELECT statement that selects all the rows from the EMP_ACT table into your tables named REFERENCES_TABLE and COST_TABLE. Tag the entries that contain this information with the reference number 1500.

       EXPLAIN REFERENCE, COST
       SET QUERYNO = 1500
       FOR SELECT * FROM EMP_ACT

FETCH

The FETCH statement positions a cursor on the next row of its result table and assigns the values of that row to host variables, host structures, or both.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared.

Authorization

See DECLARE CURSOR for an explanation of the authorization required to use a cursor.

Syntax



>>-FETCH--cursor_name----+-INTO----host_variable_list---------+-><
                         '-USING DESCRIPTOR--descriptor_name--'
 

Description

cursor_name
Identifies the select cursor to be used in the fetch operation. The cursor_name must identify a declared cursor as explained in DECLARE CURSOR. When the FETCH statement is processed, the cursor must be in the open state.

If the cursor is currently positioned on or after the last row of the result table:

If the cursor is currently positioned before a row, the cursor is positioned on that row, and the values of that row are assigned to host variables and host structure subfields as specified by INTO or USING.

If the cursor is currently positioned on a row other than the last row, after execution of the FETCH statement the cursor is positioned on the next row. Values of that row are assigned to host variables and host structure subfields as specified by INTO or USING.

INTO
Introduces a list of host variables, host structures, or both.

host_variable_list
Identifies one or more host variables, host structures, or both, that must be declared in the program in accordance with the rules for declaring host variables and host structures.

The first value in the result row is assigned to the first host variable or host structure subfield in the list, the second value to the second variable or subfield, and so on.

USING DESCRIPTOR descriptor_name
Identifies an output SQLDA that must contain a valid description of zero or more host variables.

Before the FETCH statement is processed, the user must set some fields in the SQLDA as described in the "Description" section of EXECUTE and Table 20.

The data type of a variable must be compatible with its corresponding value. If the value is numeric, the variable must have the capacity to represent the whole part of the value. For a datetime value, the variable must be a character string variable of a minimum length as defined in String Representations of Datetime Values. If the value is null, an indicator variable must be specified.

Each value with a corresponding variable is assigned to the variable in accordance with the assignment rules described in Chapter 3, "Language Elements". If the number of variables is less than the number of values in the row, the SQLWARN3 field of the SQLCA is set to 'W'. If an assignment error occurs, the value is not assigned to the variable, and no more values are assigned to variables. Any values that have already been assigned to variables remain assigned.

Error Conditions

See the DB2 Server for VSE & VM Application Programming manual for a description of the possible errors when FETCH is processed.

Notes

Cursor Positioning

An open cursor has three possible positions:

If a cursor is on a row, that row is called the current row of the cursor. A cursor referenced in an UPDATE or DELETE statement must be positioned on a row. A cursor can only be on a row as a result of a FETCH statement.

It is possible for an error to occur that makes the state of the cursor unpredictable.

Examples

There are two tables, FORUM and ARCHIVE, each with the following columns:
Name: FORUM RECEIVED SOURCE TOPIC ENTRY_TEXT
Type:
char(8)
not null


timestamp
not null


char(8)
not null


char(64)
not null


varchar(4000)
not null

Desc: Forum name Date and time entry received Userid of person appending entry Topic within the forum The text appended in this entry

The FORUM table contains a number of named forums. Each forum contains one or more topics and each topic contains one or more entries. When a topic is no longer current its entries are either deleted or moved to the ARCHIVE table.

The following PL/I program performs maintenance on the forum table. A user can invoke the program with one of three commands. Each command is accompanied by a string of text that can be found within the TOPIC column of the entries for a given topic (this need not be the entire TOPIC value). The three commands are:

  CLEANUP:  PROC OPTIONS(MAIN);
      DCL NOT_END BIT(1);
      DCL  ACTION       BINARY FIXED(15);   /* 1=chg-topic   2=archive   3=delete */
    EXEC SQL  BEGIN DECLARE SECTION;
      DCL  SRCH_FORUM   CHAR(8);
      DCL  SRCH_TOPIC   CHAR(66) VARYING;
      DCL  NEW_TOPIC    CHAR(64) VARYING;
      DCL  FORUM        CHAR(8);
      DCL  1 ENTRY,
             5 TSTMP    CHAR(26),
             5 PERSON   CHAR(8),
             5 TOPIC    CHAR(64) VARYING;
      DCL  TXT          CHAR(4000) VARYING;
    EXEC SQL  END DECLARE SECTION;
    EXEC SQL  INCLUDE SQLCA;
    EXEC SQL  WHENEVER NOT FOUND CONTINUE;
    EXEC SQL  WHENEVER SQLWARNING CONTINUE;
    EXEC SQL  WHENEVER SQLERROR GOTO ERRCHK;
 
    EXEC SQL  CONNECT TO TOROLAB3;
    GET LIST (ACTION, SRCH_FORUM, SRCH_TOPIC, NEW_TOPIC);
    SRCH_TOPIC = '%' || SRCH_TOPIC || '%';
    EXEC SQL  DECLARE CUR CURSOR FOR
                     SELECT * FROM FORUM
                       WHERE FORUM = :SRCH_FORUM AND TOPIC LIKE :SRCH_TOPIC
                       FOR UPDATE OF TOPIC;
    EXEC SQL  OPEN CUR;
    EXEC SQL  FETCH CUR INTO :FORUM, :ENTRY, :TXT;
    IF SQLSTATE = '02000'
      THEN DO;
        DISPLAY ('No notes found for requested forum and topic');
        GO TO FINISHED;
      END;
 
    NOT_END = '1'B;
    DO WHILE (NOT_END);
      EXEC SQL  FETCH CUR INTO :FORUM, :ENTRY, :TXT;
      IF SQLSTATE = '02000' THEN
        NOT_END = '0'B;
      ELSE DO;
        SELECT;
          WHEN (ACTION = 1)                /* change topic value */
            EXEC SQL  UPDATE FORUM
                        SET TOPIC = :NEW_TOPIC
                        WHERE CURRENT OF CUR;
          WHEN (ACTION = 2)                /* archive entry to another table */
            DO;
              EXEC SQL  INSERT INTO ARCHIVE
                          VALUES (:FORUM, :TSTMP, :PERSON, :TOPIC, :TXT);
              EXEC SQL  DELETE FROM FORUM WHERE CURRENT OF CUR;
            END;
          WHEN (ACTION = 3)                /* delete topic */
            EXEC SQL  DELETE FROM FORUM WHERE CURRENT OF CUR;
        END; /* select */
      END;  /* else do */
    END;  /* do while */
 
  FINISHED:
    EXEC SQL  CLOSE CUR;
    EXEC SQL  COMMIT WORK;
    RETURN;
  ERRCHK:
    DISPLAY ('Unexpected Error -changes will be backed out');
    PUT SKIP LIST (SQLCA);
    EXEC SQL  WHENEVER SQLERROR CONTINUE;  /* continue if error on rollback */
    EXEC SQL  ROLLBACK WORK;
    RETURN;
  END;  /* CLEANUP */

Extended FETCH

The Extended FETCH statement positions a cursor on the next row of its result table and assigns the values of that row to host variables. The cursor must have been opened using the Extended OPEN statement.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the statement must have one of the following:

Syntax



>>-FETCH--cursor_variable--USING DESCRIPTOR--descriptor_name---><
 

Description

cursor_variable
Identifies the cursor that is to be used. The cursor must have been defined by a preceding Extended DECLARE CURSOR statement in the same logical unit of work.

USING DESCRIPTOR descriptor_name
Identifies an output SQLDA that must contain a valid description of host variables.

Before the Extended FETCH statement is processed, the user must set some fields in the SQLDA as described in the "Description" section of EXECUTE and Table 20.

The indicated cursor must be declared and opened.

Notes

In most respects, the Extended FETCH statement is identical to the FETCH statement (see FETCH). However, in the Extended FETCH statement, the cursor_name is a host variable, thereby making it possible for a user to provide the cursor name when the program is run and to FETCH in a logical unit of work or program other than the one in which the statement was prepared. Extended DECLARE CURSOR, OPEN, and FETCH must occur in the same logical unit of work.

Examples

FETCH :CURSOR1 USING DESCRIPTOR MYSQLDA

GRANT (Package Privileges)

This form of the GRANT statement grants the privilege to process statements in a package.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

To process this statement, the privileges held by the authorization ID of the statement must include the EXECUTE privilege on the package and GRANT authority on that privilege. Someone with DBA authority may grant the EXECUTE privilege on a package owned by another user.

Syntax



                    (1)
>>-GRANT EXECUTE ON-------package_name-------------------------->
 
         .-,-----------------------.
         V                         |
>----TO----+-authorization_name-+--+--+-------------------+----><
           '-PUBLIC-------------'     '-WITH GRANT OPTION-'
 


Notes:



  1. RUN can be specified as a synonym for EXECUTE to support applications
    developed for previous releases of SQL/DS.


Description

EXECUTE ON package_name
Identifies the package upon which the EXECUTE privilege is being granted. The package_name must identify a package that exists at the application server.

TO
Specifies to whom the privileges are granted.

authorization_name,...
Lists one or more authorization IDs. You cannot use the ID of the GRANT statement itself; you cannot grant privileges to yourself.

PUBLIC
Grants the EXECUTE privilege on the package to all users.

WITH GRANT OPTION
Allows the named authorization_names to grant the EXECUTE privilege on the package to other users.

If WITH GRANT OPTION is omitted, the named authorization_names cannot grant the EXECUTE privilege to others unless they have received that authority from some other source.

The GRANT authority cannot be passed to PUBLIC. If you use PUBLIC and WITH GRANT OPTION together, the statement is processed; but a warning is given and the EXECUTE privilege is granted to PUBLIC without GRANT authority.

Notes

Only the authorization ID that preprocesses a package (or an authorization ID with DBA authority) can drop that package from the database. A 'drop' privilege cannot be granted to another authorization ID.

Examples

Example 1

Grant the ability to process the TIMESHEET package (which is used by the TIMESHEET program) to everyone.

   GRANT EXECUTE ON TIMESHEET TO PUBLIC

Example 2

Grant the ability to process the TABB package (which is used by the TABB program) to KING, BROWN, and BLACK. Allow them to grant this privilege to others.

   GRANT EXECUTE ON TABB
     TO KING, BROWN, BLACK
     WITH GRANT OPTION

GRANT (System Authorities)

This form of the GRANT statement changes passwords and authorities.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

DBA authority is needed to grant authorities and to change others' passwords. DBA authority is not needed for someone to change their own password if they have been granted connect authority explicitly by a DBA. (A user able to access the database only because connect authority has been granted to ALLUSERS cannot use this command to change their own password.)

Syntax



>>-GRANT-------------------------------------------------------->
 
>-----+--+-CONNECT--+--TO----| AUTH |--+--------+----------+---><
      |  +-DBA------+                  '-| ID |-'          |
      |  '-RESOURCE-'                                      |
      |             .-,-----------------------.            |
      |             V                         |            |
      +-CONNECT TO----+-authorization_name-+--+------------+
      |               |          (1)       |               |
      |               '-ALLUSERS-----------'               |
      '-SCHEDULE TO--subsystemid--IDENTIFIED BY--password--'
 
AUTH
 
    .-,---------------------.
    V                       |
|------authorization_name---+-----------------------------------|
 
ID
 
                   .-,-----------.
                   V             |
|---IDENTIFIED BY-----password---+------------------------------|
 


Notes:



  1. ALLUSERS can only be specified once and is not applicable to a VSE
    application server.


Description

CONNECT
Grants CONNECT authority to the specified authorization_names. A user can use this parameter with the IDENTIFIED BY clause to change his or her own password.

DBA
Grants DBA authority to the specified authorization_names. This also means that the specified authorization_names will be automatically granted CONNECT and RESOURCE authority. Someone with DBA authority has all privileges on all objects in the database, including the authority to drop any object. However, a DBA may not grant any privileges on an object the DBA does not own unless the owner has given the DBA that right. A DBA also cannot revoke any privilege on an object unless the DBA granted that privilege in the first place. For a complete description of DBA authority, see the DB2 Server for VSE & VM Database Administration manual.

RESOURCE
Grants RESOURCE authority to the specified user(s). This also means that the specified user(s) will be automatically granted CONNECT authority. Someone with RESOURCE authority has the ability to create tables in public dbspaces.

TO
Introduces a list of one or more authorization_names

authorization_name
An authorization id.

ALLUSERS
Specifies that the CONNECT authority is granted implicitly to every system-defined user. Granting CONNECT to ALLUSERS is a special case that establishes implicit connect capability for all users in the system when operating under the DB2 Server for VM environment.
VSE Users

ALLUSERS is not a valid option since implicit CONNECT authority is not applicable to VSE application servers.

IDENTIFIED BY password...
Adds or changes the password for each authorization_name specified. If you specify IDENTIFIED BY, you must include a password for every authorization_name specified. The password specifies the new or changed password for each of the specified authorization_names. Passwords are limited to eight characters. The passwords and authorization_names must correspond as shown in example 2 below. If the password is the same as the one that currently exists for the authorization_name, or if no passwords are specified, the change has no real effect.

SCHEDULE
Grants the authority to connect users without specifying a password. Used with the VSE Guest Sharing facility. For more information, see the DB2 Server for VM System Administration or the DB2 Server for VSE System Administration manual.

TO subsystemid
The subsystem ID of the CICS subsystem running under the VSE guest.

IDENTIFIED BY password
The new or changed password by which the subsystem will identify itself.

Examples

Example 1

Grant DBA authority to THOMPSON and THORN.

  GRANT DBA TO THOMPSON, THORN

Example 2

Grant CONNECT authority to BRIAN (with the password CONCON), ED (with the password NDPNDP), and JOHN (with the password LIBLIB).

  GRANT CONNECT TO BRIAN, ED, JOHN
    IDENTIFIED BY CONCON, NDPNDP, LIBLIB

GRANT (Table Privileges)

This form of the GRANT statement grants privileges on table and views.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include the privilege being granted and GRANT authority on that privilege. Someone with DBA authority may grant table privileges on a table or view owned by another user.

Syntax



>>-GRANT-------------------------------------------------------->
 
>-----+-ALL--+------------+------------------------------+------>
      |      '-PRIVILEGES-'                              |
      |  .-,-------------------------------------------. |
      |  V         (1)                                 | |
      '----+-ALTER----------------------------------+--+-'
           +-DELETE---------------------------------+
           |       (1)                              |
           +-INDEX----------------------------------+
           +-INSERT---------------------------------+
           |            (1)                         |
           +-REFERENCES-----------------------------+
           +-SELECT---------------------------------+
           '-UPDATE--+----------------------------+-'
                     |    .-,--------------.      |
                     |    V                |      |
                     '-(-----column_name---+---)--'
 
                              .-,-----------------------.
                              V                         |
>----ON--+-table_name-+---TO----+-authorization_name-+--+------->
         '-view_name--'         '-PUBLIC-------------'
 
>----+-------------------+-------------------------------------><
     '-WITH GRANT OPTION-'
 


Notes:



  1. The ALTER, INDEX and REFERENCES options do not apply to views.


Description

ALL or ALL PRIVILEGES
Grants table privileges on the table or view identified in the ON clause. The privileges granted are those possessed by the authorization ID of the GRANT statement. ALL PRIVILEGES is the default.

ALTER
Grants the privilege to use the ALTER TABLE statement. This privilege cannot be granted on a view.

DELETE
Grants the privilege to use the DELETE statement.

INDEX
Grants the privilege to use the CREATE INDEX statement. This privilege cannot be granted on a view.

INSERT
Grants the privilege to use the INSERT statement.

REFERENCES
Grants the privilege to create, drop, activate, or deactivate a referential constraint in which the table is the parent table. This privilege does not apply to views.

This privilege is required to reference the parent table when a referential constraint is defined or added by the CREATE TABLE or ALTER TABLE statement respectively.

This privilege is also required on the parent table when the user wants to use the ALTER TABLE statement to drop, activate, or deactivate a foreign key on a dependent table that references the parent table.

SELECT
Grants the privilege to use the SELECT statement or the CREATE VIEW statement.

UPDATE
Allows the grantee(s) to update the table or view.

(column_name,...)
Restricts the update privilege to the columns listed. If a list of column names is not specified or if UPDATE is granted using the specification of ALL PRIVILEGES, the grantee(s) may update all updateable columns of the table, even those created later by the ALTER TABLE statement.

ON table_name  or  view_name
Identifies the table or view upon which you are granting the privileges. The table_name or view_name must identify a table or view that exists at the application server.

TO
Indicates to whom the privileges are granted.

authorization_name,...
Lists one or more authorization IDs. The ID of the GRANT statement itself cannot be used. (Privileges cannot be granted to oneself.)

PUBLIC
Grants the privileges to all users.

WITH GRANT OPTION
Allows the named authorization_names to grant the privileges to other authorization_names. If you omit WITH GRANT OPTION, the named authorization_names cannot grant the privileges to others unless they have that authority from some other source.

You cannot pass the GRANT authority to PUBLIC. If you use PUBLIC and WITH GRANT OPTION together, the statement is processed; but a warning is given and the privileges are granted to PUBLIC without GRANT authority.

Examples

Example 1

Given that you have DBA authority, and that you have all grant authorities on the table WESTERN_COURSES (owned by KATHLEEN), grant all privileges on the table to PUBLIC.

  GRANT ALL ON KATHLEEN.WESTERN_COURSES
    TO PUBLIC

Example 2

Grant the appropriate privileges on your CALENDAR table so that ROANNA and EMMA can read it and insert new entries into it, but do not allow them to change or remove any entries. Do not allow ROANNA or EMMA to grant those privileges to others.

  GRANT SELECT, INSERT ON CALENDAR
    TO ROANNA, EMMA

Example 3

Grant the UPDATE privilege on the RATING and CRITIQUE columns from the public table TORONTO_RESTAURANT (owned by ONTARIO) to MARGARET and COMPDEPT. Allow them to grant those privileges to others.

GRANT UPDATE (RATING, CRITIQUE) ON ONTARIO.TORONTO_RESTAURANT
  TO MARGARET, COMPDEPT
  WITH GRANT OPTION

INCLUDE

The INCLUDE statement inserts declarations, statements, or both, into a source program.

Invocation

This statement can only be embedded in an application program. It is not an executable statement. It is not supported in REXX.

Authorization

None required.

Syntax



>>-INCLUDE----+-SQLCA----------+-------------------------------><
              +-SQLDA----------+
              '-text_file_name-'
 

Description

SQLCA
Indicates the description of an SQL communication area (SQLCA) is to be included. INCLUDE SQLCA must not be specified more than once in the same program. INCLUDE SQLCA must not be specified if the program includes a stand-alone SQLCODE (see SQL Return Codes). For a description of the SQLCA, see SQL Communication Area (SQLCA).

SQLDA
Indicates the description of an SQL descriptor area (SQLDA) is to be included. SQLDA should not be specified in a COBOL, or FORTRAN program, as it will be interpreted as a text_file_name. For a description of the SQLDA, see SQL Descriptor Area (SQLDA).

text_file_name
Identifies an external source file to be used as input when your program is precompiled.

The statements contained in the external source specified by text_file_name may be host language statements or SQL statements (except for another INCLUDE statement). INCLUDE text_file_name statements may not be nested, but the external source may contain INCLUDE SQLDA or INCLUDE SQLCA statements. The INCLUDE text_file_name may appear in an SQL DECLARE section or the entire SQL DECLARE section(s) may be placed within an external source file.

Notes

The INCLUDE statement may be used to obtain secondary input from a CMS file in VM or a source member in VSE. If a source program input to a preprocessor uses the INCLUDE facility, any files to be used as secondary input must be accessed by the user. The INCLUDE statement causes input to be read from the specified file name until the end of the file, at which time the SYSIN input in VM or the SYSIPT input in VSE resumes.

In VM

The file to be included must have one of the following file types:

  Language
  File Type
  Assembler
  ASMCOPY
  C
  CCOPY
  COBOL
  COBCOPY
  FORTRAN
  FORTCOPY
  PL/I
  PLICOPY

In VSE

The source member must be cataloged as one of the following source types:

  Language
  Source Type
  Assembler
  A
  C
  B
  COBOL
  C
  FORTRAN
  G
  PL/I
  P

For COBOL programs, INCLUDE SQLCA must not be specified in other than the Working Storage Section.

See the DB2 Server for VSE & VM Application Programming manual for more information on using external source files.

Examples

Include an SQL Communications Area into a PL/I program.

  EXEC SQL  INCLUDE SQLCA;

INSERT

The INSERT statement inserts rows into a table or view. Inserting a row into a view also inserts the row into the table on which the view is based.

There are two forms of this statement:

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

The INSERT privilege on a view is only inherent in DBA authority. Ownership of a view does not necessarily include the INSERT privilege on the view because the privilege may not have been granted when the view was created, or it may have been granted, but subsequently revoked.

If a subselect is specified, the privileges held by the authorization ID of the statement must also include at least one of the following:

Syntax



>>-INSERT INTO----+-table_name-+-------------------------------->
                  '-view_name--'
 
>-----+----------------------------+---------------------------->
      |    .-,--------------.      |
      |    V                |      |
      '-(-----column_name---+---)--'
 
                   .-,-----------------------.
                   V                         |
>-----+-VALUES--(----+-constant-----------+--+---)--+----------><
      |              +-host_variable_list-+         |
      |              +-NULL---------------+         |
      |              '-special_register---'         |
      '-subselect--+---------------+----------------'
                   '-WITH--+-RR-+--'
                           '-CS-'
 

Description

INTO table_name

INTO view_name
Identifies the object of the insert operation. The name must identify a table or view that exists at the application server, but it must not identify a catalog table, a view of a catalog table, or a read-only view (see Read-only views). However, someone with DBA authority may insert rows into a few of the catalog tables. See Updateable Columns.

A value cannot be inserted into a view column that is derived from:

If the object of the insert operation is a view with such columns, a list of column names must be specified, and the list must not identify these columns.

(column_name,...)
Specifies the columns for which insert values are provided. Each name must be an unqualified name that identifies a column of the table or view. The same column must not be identified more than once. A view column that cannot accept insert values must not be identified.

Omission of the column list is an implicit specification of a list in which every column of the table or view is identified in left-to-right order. This list is established when the statement is prepared and therefore does not include columns that were added to a table after the statement was prepared.

SQL statements can be implicitly or explicitly rebound (prepared again). The effect of a rebind on INSERT statements that do not include a column list is to re-establish the list. Therefore, the number of columns into which data will be inserted may change.

VALUES
Introduces one row of values to be inserted. The values of the row are the values of the constants, host variables, host structure subfields, and keywords specified in the clause.

Each host variable and host structure named must be described in the program in accordance with the rules for declaring host variables and host structures.

The number of values in the VALUES clause must equal the number of names in the column list. The first value is inserted in the first column in the list, the second value in the second column, and so on.

For an explanation of constant and host-variable-list, see Chapter 3, "Language Elements". For a description of special-register, see Special Registers. NULL specifies the null value. A constant or special register cannot be used to specify the insert value for a long string column.

subselect
Inserts the rows of the result table of a subselect. There may be one, more than one, or none. If there are none, SQLCODE is set to +100 and SQLSTATE is set to '02000'.

(For an explanation of subselect, see Chapter 5, Queries.)

The base object of the INSERT, and the base object of the subselect, or any subquery of the subselect, must not be the same table.

The number of columns in the result table must equal the number of names in the column list. The value of the first column of the result is inserted in the first column in the list, the second value in the second column, and so on.

A non-null value cannot be inserted into a long string column using a subselect.

WITH
Specifies the isolation level at which the subselect is executed.

RR
Repeatable read

CS
Cursor stability

The default isolation level of the statement is the isolation level of the package.

INSERT Rules

Insert values must satisfy the following rules. If they do not, or if any other errors occur during the execution of the INSERT statement, no rows are inserted.

If you are inserting rows into a parent table that is part of a referential constraint, the database manager implicitly checks that the primary key remains unique and does not contain null values.

Notes

Rows are inserted in an order determined by the database manager; that is, no facility is provided to specify the position in the table of a newly inserted row.

If an error occurs during the execution of an INSERT, you must inspect SQLWARN6 to determine the extent of the error. The following are current settings for SQLWARN6 when there is an error indication and the possible responses:

  1. SQLWARN6 is set to 'S'. A severe error has occurred, leaving the system in an unusable state.
  2. SQLWARN6 is set to 'W'. An error occurred causing the LUW to be rolled back automatically. The system is still in a usable state. The application can either:
  3. SQLWARN6 is blank. An error has occurred, but the LUW is still active. For recoverable pools, any changes made by the request have been rolled back, hence the failing request has not left any partial results in the database. For information on nonrecoverable storage pools, see the DB2 Server for VM System Administration or the DB2 Server for VSE System Administration manual. The application can do one of the following:

The order of rows being inserted is determined by the database manager; no facility is provided to specify the position in the table of a newly inserted row. The SQLERRD(3) portion of the SQLCA indicates the number of rows that were inserted.

Unless appropriate locks already exist, one or more exclusive locks are acquired at the execution of a successful INSERT statement. Until the locks are released, an inserted row can only be accessed by the application process that performed the insert. For further information about locking, see the description of the COMMIT, ROLLBACK, LOCK TABLE, and LOCK DBSPACE statements.

Examples

Example 1

Insert a new department with the following specifications into the DEPARTMENT table:

  INSERT INTO DEPARTMENT
    VALUES ('E31', 'ARCHITECTURE', '00390', 'E01')

Example 2

Insert a new department into the DEPARTMENT table as in example 1, but do not assign a manager to the new department.

  INSERT INTO DEPARTMENT (DEPTNO, DEPTNAME, ADMRDEPT)
    VALUES ('E31', 'ARCHITECTURE', 'E01')

Example 3

Create a temporary table MA_EMP_ACT with the same columns as the EMP_ACT table. Load MA_EMP_ACT with the rows from the EMP_ACT table with a project number (PROJNO) starting with the letters 'MA'.

  CREATE TABLE MA_EMP_ACT
        (EMPNO     CHAR(6)  NOT NULL,
         PROJNO    CHAR(6)  NOT NULL,
         ACTNO     SMALLINT  NOT NULL,
         EMPTIME   DEC(5,2),
         EMSTDATE  DATE,
         EMENDATE  DATE )
  INSERT INTO MA_EMP_ACT
    SELECT * FROM EMP_ACT
      WHERE SUBSTR(PROJNO, 1, 2) = 'MA'

Example 4

Use a PL/I program statement to add a skeleton project to the PROJECT table. Obtain the project number (PROJNO), project name (PROJNAME), department number (DEPTNO), and responsible employee (RESPEMP) from host variables and a host structure. Use the current date as the project start date (PRSTDATE). Assign a NULL value to the remaining columns in the table.

  .
  .
  DCL 1 PROJECT,
        5 PRJNO   CHAR(5),
        5 PRJNM   CHAR(24) VARYING;
  DCL 1 EMPLOYEE,
        5 DPTNO   CHAR(3),
        5 REMP    CHAR(6),
        5 LNAME   CHAR(25);
  .
  .
  .
  EXEC SQL  INSERT INTO PROJECT  (  PROJNO, PROJNAME, DEPTNO, RESPEMP, PRSTDATE)
              VALUES (:PROJECT, :EMPLOYEE.DPTNO, :REMP, CURRENT DATE);

LABEL ON

The LABEL ON statement adds or replaces labels in the catalog descriptions of tables, views, or columns.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

Syntax



>>-LABEL ON----------------------------------------------------->
 
>-----+--| options_a |------------------------IS--string_constant----+>
      |                      .-,-----------------------------------.     |
      |                      V                                     |     |
      '--+-table_name-+---(-----column_name--IS--string_constant---+---)-'
         '-view_name--'
 
>--------------------------------------------------------------><
 
options_a
 
|--+-TABLE--+-table_name-+--------------+-----------------------|
   |        '-view_name--'              |
   '-COLUMN--+-table_name.column_name-+-'
             '-view_name.column_name--'
 

Description

TABLE
Indicates that the label is for a table or a view.

table_name

view_name
Identifies a table or view to which the label applies. The name must identify a table or view at the application server.

The label is placed into the TLABEL column of the SYSTEM.SYSCATALOG catalog table for the row that describes the table or view.

COLUMN
Indicates that the label is for a column.

table_name.column_name

view_name.column_name
Identifies the column, qualified by the name of the table or view in which it appears. The column_name must identify a column of the specified table or view that exists at the application server.

The label is placed in the CLABEL column of the SYSTEM.SYSCOLUMNS catalog table, for the row that describes the column.

Multiple Labels:
To define a label for more than one column within the same table or view within the same statement, the table or view name is followed by a list of one or more column_name and string-constant pairs in parentheses.

The column_name must identify a column of the specified table or view that exists at the application server.

IS
Introduces the label you want to provide.

string_constant
Can be any SQL character string constant of up to 30 characters. The constant may contain mixed double-byte and single-byte characters.

Notes

Unlike synonyms, labels cannot be used as identifiers. Instead, they can be used in displays created by applications that process SQL statements dynamically.

A DESCRIBE statement specified with USING BOTH or USING LABELS can be used to return column labels in an SQLDA. The program can then move the label from the SQLNAME field of the SQLDA into a work area. A column is considered to have no label if either its LABEL column in SYSTEM.SYSCOLUMNS is NULL, or if it has a zero length value. If there is no column label when the program issues a DESCRIBE, the SQLNAME field of the SQLDA is set to length 0, and the field is cleared to 30 blanks. For this reason, the program should move the label into a work area using the length returned in SQLDA only after it makes sure that the length is not zero.

Examples

Example 1

Insert a label for the EMP_ACT table into the catalog.

  LABEL ON TABLE EMP_ACT
    IS 'EMPLOYEE ACTIVITY BY PROJECT'

Example 2

Insert a label for the EMP_VIEW1 view into the catalog.

  LABEL ON TABLE EMP_VIEW1
    IS 'EMPLOYEE WITHOUT SALARY'

Example 3

Insert a label for the EDLEVEL column of the EMPLOYEE table into the catalog.

  LABEL ON COLUMN EMPLOYEE.EDLEVEL
    IS 'HIGHEST GRADE LEVEL'

Example 4

Insert a label for two different columns of the EMPLOYEE table into the catalog.

  LABEL ON EMPLOYEE
    (WORKDEPT IS 'DEPTNO IN EMPLOYEE',
           EDLEVEL  IS 'HIGHEST GRADE LEVEL ')

LOCK DBSPACE

The LOCK DBSPACE statement either prevents concurrent application processes from changing a dbspace or prevents concurrent application processes from using a dbspace.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

Syntax



>>-LOCK DBSPACE--dbspace_name--IN----+-SHARE-----+--MODE-------><
                                     '-EXCLUSIVE-'
 

Description

dbspace_name
Identifies the dbspace to be locked. The dbspace must exist at the application server. You cannot lock any dbspace containing the database manager's system catalog.

The LOCK statement can be used to lock both private and public dbspaces. If the dbspace_name is unqualified, the database manager will first look for a private dbspace and, if that does not exist, it will look for a public dbspace with the same dbspace name.

IN SHARE MODE
Prevents concurrent application processes from executing any but read-only operations on the dbspace.

IN EXCLUSIVE MODE
Prevents concurrent application processes from executing any operations on the dbspace. This option requires a Z lock on the dbspace.

Locking prevents concurrent operations. A lock is not necessarily acquired during the execution of LOCK DBSPACE if a suitable lock already exists. The lock that prevents the concurrent operations is held until the termination of the unit of work.

Examples

Obtain a lock on the dbspace named DSP3. Allow others to read from the DSP3 while it is locked.

  LOCK DBSPACE DSP3 IN SHARE MODE

LOCK TABLE

The LOCK TABLE statement either prevents concurrent application processes from changing a table or prevents concurrent application processes from using a table.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

Syntax



>>-LOCK TABLE--table_name--IN----+-SHARE-----+--MODE-----------><
                                 '-EXCLUSIVE-'
 

Description

table_name
Identifies the table. The table_name must identify a base table that exists at the application server. If you lock a table in a private dbspace the entire dbspace is locked because locking is always performed at the dbspace level for private dbspaces.

IN SHARE MODE
Prevents concurrent application processes from executing any but read-only operations on the table.

IN EXCLUSIVE MODE
Prevents concurrent application processes from executing any operations on the table. This option requires an IX lock on the dbspace and a Z lock on the table.

Locking prevents concurrent operations. A lock is not necessarily acquired during the execution of LOCK TABLE if a suitable lock already exists. The lock that prevents the concurrent operations is held until the termination of the unit of work.

The lock is acquired when the LOCK TABLE statement is processed.

Examples

Obtain a lock on the DEPARTMENT table. Do not allow others to either update or read from DEPARTMENT while it is locked.

  LOCK TABLE DEPARTMENT IN EXCLUSIVE MODE

OPEN

The OPEN statement opens a cursor.

Invocation

This statement can be embedded only in an application program. It is an executable statement that cannot be dynamically prepared.

Authorization

See DECLARE CURSOR for the authorization required to use a cursor. The authorization for the OPEN statement is checked when the related DECLARE CURSOR statement is prepared.

Syntax



>>-OPEN--cursor_name----+------------------------------------+-><
                        +-USING----host_variable_list--------+
                        '-USING DESCRIPTOR--descriptor_name--'
 

Description

cursor_name
Identifies the cursor to be opened. The cursor_name must identify a declared cursor as explained in the Notes for the DECLARE CURSOR statement. When the OPEN statement is processed, the cursor must be in the closed state, and it must have been successfully prepared or declared.

If using an insert-cursor and the program is blocking, this statement tells the application server to prepare to block the rows to be inserted. If not blocking, the application server prepares to insert a single row into the database. Rows are not actually inserted into the database until one or more PUT statements have been processed.

If opening a query-cursor, the result table of the cursor is derived by evaluating that select-statement. The evaluation uses the current values of any special registers specified in the select-statement and the current values of any host variables or host structures specified in it or in the USING clause of the OPEN statement. The rows of the result table may be derived during the execution of the OPEN statement, and a temporary table created to hold them; or they may be derived during the execution of subsequent FETCH statements. In either case, the cursor is placed in the open state and positioned before the first row of its result table. If the table is empty, the position of the cursor is effectively "after the last row."

USING
Introduces a list of host variables or hsot structures or both whose values are substituted for the parameter markers (question marks) of a prepared statement. (For an explanation of parameter markers, see PREPARE.) If the DECLARE CURSOR statement names a prepared statement that includes parameter markers, you must use USING. If the prepared statement does not include parameter markers, USING is ignored. USING must not be used if the select-statement of the cursor is specified in the DECLARE CURSOR statement.

A USING clause cannot appear in the OPEN statement for an insert-cursor.

host_variable_list
Identifies a list of host variables, host structures, or both, that must be declared in the program in accordance with the rules for declaring host variables and host structures.

The total number of host variables and host structure subfields must be the same as the number of parameter markers in the prepared statement. The nth variable or subfield corresponds to the nth parameter marker in the prepared statement.

USING DESCRIPTOR descriptor_name
Identifies an input SQLDA that must contain a valid description of host variables.

Before the OPEN statement is processed, the user must set some fields in the SQLDA as described in the "Description" section of EXECUTE and Table 20.

If the select-statement of the cursor was prepared (rather than declared) and that statement contains parameter markers, when that statement is evaluated each parameter marker in the statement is effectively replaced by its corresponding host variable. With the exception of the LIKE predicate, the replacement of a parameter marker is an assignment operation in which the source is the value of the host variable, and the target is a variable within the database manager. The attributes of the target variable are determined as follows:

If the parameter marker is the pattern in a LIKE predicate, then:

Let V denote a host variable that corresponds to parameter marker P. The value of V is assigned to the target variable for P in accordance with the rules for assigning a value to a column. Thus:

When the SELECT statement of the cursor is evaluated, the value used in place of P is the value of the target variable for P. For example, if V is CHAR(6), and the target is CHAR(8), the value used in place of P is the value of V padded with two blanks.

The USING clause is intended for a prepared SELECT statement that contains parameter markers. However, it can also be used when the SELECT statement of the cursor is part of the DECLARE CURSOR statement. In this case the OPEN statement is processed as if each host variable in the SELECT statement were a parameter marker, except that the attributes of the target variables are the same as the attributes of the host variables in the SELECT statement. The effect is to override the values of the host variables in the SELECT statement of the cursor with the values of the host variables specified in the USING clause.

Notes

Closed state of cursors

All cursors in a program are in the closed state when:

A cursor can also be in the closed state because:

To retrieve rows from the active set of a query-cursor, a FETCH statement must be processed while the cursor is open. To insert rows into the active set of an insert-cursor, a PUT statement must be processed while the cursor is open. The only way to change the state of a cursor from closed state to open is to process an OPEN statement.

Effect of temporary tables

If the result table of a query cursor is not read-only, its rows are derived during the execution of subsequent FETCH statements. The same method may be used for a read-only result table. However, if a result table is read-only, the database manager may choose to use the temporary table method instead. With this method the entire result table is inserted into a temporary table during the execution of the OPEN statement. When a temporary table is used, the results of a program can differ in these two ways:

Conversely, if a temporary table is not used, INSERT, UPDATE, and DELETE statements processed while the cursor is open can affect the result table if issued from the same application process. The effect of such operations is not always predictable. For example, if cursor C is positioned on a row of its result table defined as SELECT * FROM T, and you insert a row into T, the effect of that insert on the result table is not predictable because its rows are not ordered. A subsequent FETCH C might or might not retrieve the new row of T.

Examples

Example 1

Write the embedded statements in a COBOL program that will:

  1. Define a cursor C1 that is to be used to retrieve all rows from the DEPARTMENT table for departments that are administered by (ADMRDEPT) department 'A00'
  2. Place the cursor C1 before the first row to be fetched.

  EXEC SQL  DECLARE C1 CURSOR FOR
              SELECT DEPTNO, DEPTNAME, MGRNO FROM DEPARTMENT
                WHERE ADMRDEPT = 'A00'  END-EXEC.
 
  EXEC SQL  OPEN C1  END-EXEC.

Example 2

Code an OPEN statement to associate a cursor DYN_CURSOR with a dynamically defined select-statement in a PL/I program. Assume each prepared select-statement always has two parameter markers in its WHERE clause with the first having a data type of integer and the second having a data type of varchar(64). (The related host variable definitions, PREPARE statement and DECLARE CURSOR statement are also shown in the example below.)

  EXEC SQL  BEGIN DECLARE SECTION;
    DCL  HV_INT      BINARY    FIXED(31);
    DCL  HV_VCHAR64  CHAR(64)  VARYING;
    DCL  STMT1_STR   CHAR(200)  VARYING;
  EXEC SQL  END DECLARE SECTION;
 
  EXEC SQL  PREPARE STMT1_NAME FROM :STMT1_STR;
 
  EXEC SQL  DECLARE DYN_CURSOR CURSOR FOR STMT1_NAME;
 
  EXEC SQL  OPEN DYN_CURSOR USING :HV_INT, :HV_VCHAR64;

Example 3

Code an OPEN statement as in example 2, but in this case the number and data types of the parameter markers in the WHERE clause are not known.

  EXEC SQL  BEGIN DECLARE SECTION;
    DCL  STMT1_STR   CHAR(200)  VARYING;
  EXEC SQL  END DECLARE SECTION;
  EXEC SQL  INCLUDE SQLDA;
 
  EXEC SQL  PREPARE STMT1_NAME FROM :STMT1_STR;
  EXEC SQL  DECLARE DYN_CURSOR CURSOR FOR STMT1_NAME;
 
  EXEC SQL  OPEN DYN_CURSOR USING DESCRIPTOR :SQLDA;

Example 4

This example shows the SQL statements used with a cursor CURSOR3 in a PL/I program. In this program, CURSOR3 inserts a row into the MA_ACT view (and therefore into the EMP_ACT table, which is the base table for the view) based on the values in the host variables EMNUM (char(6)), PJNUM (char(6)), ACNUM (smallint), EMTIM (dec(5,2)), STDAT (date), and EMDAT (date).

  EXEC SQL  DECLARE CURSOR3 CURSOR FOR
              INSERT INTO MA_ACT
                VALUES (:EMNUM, :PJNUM, :ACNUM, :EMTIM, :STDAT, :EMDAT);
 
  EXEC SQL  OPEN CURSOR3;
 
  EXEC SQL  PUT CURSOR3;
 
  EXEC SQL  CLOSE CURSOR3;

Extended OPEN

The Extended OPEN statement opens a cursor declared using an Extended DECLARE CURSOR statement for a previously prepared statement. The open cursor retrieves the results of a query, or inserts values into the database.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the statement must have one of the following:

Syntax



>>-OPEN--cursor_variable---------------------------------------->
 
>-----+------------------------------------+-------------------><
      '-USING DESCRIPTOR--descriptor_name--'
 

Description

cursor_variable
Identifies the cursor that is to be opened. The cursor must have been defined by a preceding Extended DECLARE CURSOR statement in the same logical unit of work.

USING DESCRIPTOR descriptor_name
Identifies an input SQLDA structure that provides information concerning input variables that were specified as parameter markers (?) when the statement was prepared.

Before the Extended OPEN statement is processed, the user must set the fields in the SQLDA described in the "Description" section of EXECUTE and Table 20.

When the cursor is to be used for inserting data into a table, the USING DESCRIPTOR clause should not be included because the clause must be in the PUT statement.

Notes

In most respects, the Extended OPEN statement is similar to the OPEN statement (see OPEN). However, in the Extended OPEN statement, the cursor_name is a host variable, thereby making it possible for a user to provide the cursor name when the program is run and to open the cursor in a logical unit of work or program other than the one in which the statement was prepared. Extended DECLARE CURSOR and Extended OPEN must occur in the same logical unit of work.

Examples

OPEN :CURSOR1 USING DESCRIPTOR MYSQLDA

PREPARE

The PREPARE statement is used by application programs to dynamically prepare an SQL statement for execution. The PREPARE statement creates an executable SQL statement, called a prepared statement, from a character string form of the statement, called a statement string. The prepared statement is a named object that can be referred to only within the logical unit of work in which it is created.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared.

Authorization

The authorization rules are those defined for the SQL statement specified by the PREPARE statement. For example, see Chapter 5, Queries for the authorization rules that apply when a select-statement is prepared. The authorization ID is the run-time authorization ID.

Syntax



>>-PREPARE--statement_name--FROM----+-string_constant-+--------><
                                    '-host_variable---'
 

Description

statement_name
Provides a name for the prepared statement. No two prepared statements in a single source program may use the same statement name. In REXX, the statement_name must not be the same as the cursor_name declared in the program.

FROM
Introduces the statement string. The statement string is the value of the specified string_constant or the identified host_variable.

string_constant
String constants are supported in all languages except Assembler and C.

You should avoid using either delimited identifiers or DBCS strings in statements specified in string constants because results are unpredictable.

When the string_constant form of the PREPARE statement is used in FORTRAN programs:

  • If the statement_name is referenced in a DECLARE CURSOR statement, the PREPARE statement must come first.
  • Any unqualified objects are qualified with the authorization ID of the person preparing the program.

host_variable
Identifies a host variable that is described in the program in accordance with the rules for declaring character string variables. An indicator variable must not be specified.

In Assembler, C, COBOL, and REXX,

the host variable must be a varying-length string variable. In C, it cannot be a NUL-terminated string. In FORTRAN, the host variable must be a fixed-length string variable. In PL/I, the host variable can either be a fixed-length or varying-length string variable. The host variable must have a maximum length of 8192.

In a PL/I Version 2 program, a prepared statement containing DBCS characters must be coded as a mixed string using the new PL/I Mixed format.

For example:

  DYNSTR = 'SELECT COL1 FROM TABLE   WHERE COL2 = G'<....>'M;
  EXEC SQL PREPARE STMT1 FROM :DYNSTR;

Rules for statement strings

The string_constant or host_variable must contain one of the following SQL statements:

ACQUIRE DBSPACE
ALLOCATE CURSOR
ALTER DBSPACE
ALTER TABLE
ASSOCIATE LOCATORS
COMMENT ON
CREATE INDEX
CREATE SYNONYM
CREATE TABLE
CREATE VIEW
DELETE
DROP
EXPLAIN


GRANT Package Privileges
GRANT System Authorities
GRANT Table Privileges
INSERT
LABEL ON
LOCK DBSPACE
LOCK TABLE
REVOKE Package Privileges
REVOKE System Authorities
REVOKE Table Privileges
select-statement
UPDATE
UPDATE STATISTICS

Furthermore, the statement string must not:

Parameter markers

Although a statement string cannot include references to host variables, it may include parameter markers; those can be replaced by the values of host variables when the prepared statement is processed.

A parameter marker is a question mark (?) that is used where a host variable could be used if the statement string were a static SQL statement. For an explanation of how parameter markers are replaced by values, see OPEN and EXECUTE.

Rules for parameter markers:

Notes

When a PREPARE statement is processed, the statement string is parsed and checked for errors. If the statement string is incorrect, a prepared statement is not created and the error condition that prevents its creation is reported in the SQLCA.

Prepared statements can be referred to in the following kinds of statements, with the following restrictions shown:

  In ...
  The prepared statement ...
  DESCRIBE
  has no restrictions
  DECLARE CURSOR
  must be a select-statement or an insert-statement
  EXECUTE
  must not be a select-statement

A prepared statement can be processed many times. Indeed, if a prepared statement is not processed more than once and does not contain parameter markers, it is more efficient to use the EXECUTE IMMEDIATE statement rather than the PREPARE and EXECUTE statements.

All prepared statements created in a logical unit of work are destroyed when the logical unit of work is terminated.

Examples

Example 1

Prepare and process a non-select-statement in a COBOL program. Assume the statement is contained in a host variable HOLDER and that the program will place a statement string into the host variable based on some instructions from the user. The statement to be prepared does not have any parameter markers.

  EXEC SQL  PREPARE STMT_NAME FROM :HOLDER  END-EXEC.
 
  EXEC SQL  EXECUTE STMT_NAME  END-EXEC.

Example 2

Prepare and process a non-select-statement as in example 1, except code it for a PL/I program. Also assume the statement to be prepared can contain any number of parameter markers.

  EXEC SQL  PREPARE STMT_NAME FROM :HOLDER;
 
  EXEC SQL  EXECUTE STMT_NAME USING DESCRIPTOR :INSERT_DA;

Assume that the following statement is to be prepared:

  INSERT INTO DEPARTMENT VALUES(?, ?, ?, ?)

To insert department number G01 named COMPLAINTS, which has no manager and reports to department A00, the structure INSERT_DA should have the following values before running the EXECUTE statement.
View figure.

Extended PREPARE

The Basic Extended PREPARE and Single Row Extended PREPARE forms of the Extended PREPARE statement permit a statement to be prepared and stored in a package for later execution.

The Empty Extended PREPARE form of the Extended PREPARE statement provides support for dynamic SQL statements in non-modifiable packages. It is used in conjunction with the Temporary Extended PREPARE form of the Extended PREPARE statement.

The Temporary Extended PREPARE form of the Extended PREPARE statement provides support for dynamic SQL statements in non-modifiable packages.

The package you are preparing into must have been created with the CREATE PACKAGE statement.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the first three forms of the Extended PREPARE statement must have at least one of the following:

The authorization ID of the Temporary Extended PREPARE form must have at least one of the following:

Syntax



Basic Extended PREPARE

>>-PREPARE FROM--host_variable---------------------------------><
 
>>-SETTING--section_variable--IN--package_spec------------------>
 
>-----+------------------------------------+-------------------><
      '-USING DESCRIPTOR--descriptor_name--'
 

Single Row Extended PREPARE

>>-PREPARE SINGLE ROW FROM--host_variable----------------------><
 
>>-SETTING--section_variable--IN--package_spec------------------>
 
>-----+------------------------------------+-------------------><
      '-USING DESCRIPTOR--descriptor_name--'
 

Empty Extended PREPARE

>>-PREPARE FROM NULL SETTING--section_variable--IN--package_spec-->
 
>--------------------------------------------------------------><
 

Temporary Extended PREPARE

>>-PREPARE FROM--host_variable--FOR--section_variable----------><
 
>>-IN--package_spec--------------------------------------------><
 

Description

host_variable
Specifies the statement that is to be prepared. Host_variable is a varying-length string host variable of maximum length 8192. It does not have an associated indicator variable.

SETTING section_variable
In the Basic Extended PREPARE statement, the section_variable is set by the database manager to an identifier for the statement that is prepared. It is used in subsequent Extended DESCRIBE, DROP STATEMENT, Extended EXECUTE, and Extended DECLARE CURSOR statements to specify the corresponding prepared statement.

In the Single Row Extended PREPARE statement, the section_variable is set by the database manager to an identifier for the statement that is prepared. It is used in subsequent Extended DESCRIBE, DROP STATEMENT, and Extended EXECUTE (with the OUTPUT Descriptor clause) statements to specify the corresponding prepared statement.

In the Empty Extended PREPARE statement, the section_variable is set by the database manager to an identifier for the indefinite section that is created. It is used in subsequent Temporary Extended PREPARE, Extended DESCRIBE, Extended EXECUTE, DROP STATEMENT and Extended DECLARE CURSOR statements to specify the corresponding section.

FOR section_variable
Identifies a statement defined by an Empty Extended PREPARE statement. This should be set to the value returned by the database manager as a result of the Empty Extended PREPARE statement.

IN package_spec
Identifies the package in which the prepared statement is to be stored. If the qualified package_spec does not refer to an existing package, an error will result.

USING DESCRIPTOR descriptor_name
Identifies an input SQLDA structure that provides information concerning input variables that were specified as parameter markers (?) when the statement was prepared. Extended PREPARE only utilizes the following fields in an SQLDA: SQLD, SQLTYPE, SQLLEN, and, optionally, SQLNAME (for CCSID override).

USING DESCRIPTOR may be specified for Temporary Extended PREPARE without an error indication, but it is ignored.

Normally if a prepared statement contains parameter markers (?), an SQLDA would be provided at run time by the Extended EXECUTE or Extended OPEN statement that references that prepared statement. However, an SQLDA can be used to improve run-time performance and reduce conversions in those cases where data types and lengths are known at statement preparation time for the parameter markers in the prepared SQL statement. Another reason for providing an SQLDA at statement preparation time is to override the restrictions on the use of parameter markers as outlined under "Rules for parameter markers" under the PREPARE statement. Also, if an SQLDA is not provided at statement preparation time, it is assumed that none of the variables used within predicates are nullable; therefore, an error results if a negative indicator value is provided at execution time.

An input SQLDA may also be specified on a subsequent Extended EXECUTE or Extended OPEN; in such cases, if the information does not match that of the PREPARE SQLDA, errors may result.

The fields described in the SQLDA should match the parameter markers (?) in the statement being prepared. If there are fewer fields specified in the SQLDA, an error will result. If there are more fields specified in the SQLDA, they will be ignored.

Before the Extended PREPARE statement is processed, the user must set the fields in the SQLDA described in the "Description" section of EXECUTE and Table 20.

The Basic Extended PREPARE form of the Extended PREPARE statement adds an SQL statement to an existing package. If the package is new, the Extended PREPARE statement must be preceded by a CREATE PACKAGE statement. Existing packages, created using the MODIFY option of CREATE PACKAGE, can be extended using this format of the PREPARE statement.

The USING DESCRIPTOR clause must be used when preparing a statement that contains parameter markers, if using the DRDA protocol.

The Single Row Extended PREPARE form of the Extended PREPARE statement indicates that the select-statement contained in the host_variable is a single row Select. Select-statements prepared using "PREPARE SINGLE ROW" must be processed using the Extended EXECUTE with OUTPUT DESCRIPTOR command.

The Single Row Extended PREPARE form of the Extended PREPARE statement is not supported with the DRDA protocol.

The Empty Extended PREPARE form of the Extended PREPARE statement allows for the creation of an indefinite section in a program. The section is subsequently used when a statement is dynamically prepared using a Temporary Extended PREPARE statement.

This format of the Extended PREPARE must follow the CREATE PACKAGE...USING NOMODIFY... format of the CREATE PACKAGE statement and must exist in the same logical unit of work as the CREATE PACKAGE statement.

If the above restriction is violated, execution of the statement will be unsuccessful.

The Temporary Extended PREPARE form of the Extended PREPARE statement prepares the statement contained in the created indefinite section. This section must have been created by an Empty Extended PREPARE statement. The section number for this section is contained in the section_variable.

This format of the Extended PREPARE may not be processed in a logical unit of work in which update to the package is already in progress. If the above restriction is violated, execution of the statement will be unsuccessful.

See "Rules for statement strings", "Parameter Markers", and "Rules for parameter markers" on page *** for a list of the SQL statements which may be contained in the host_variable and the rules for using parameter markers in the host_variable.

Notes

The various formats to the Extended PREPARE statement permit statements to be created for different programs in different logical units of work.

Because a DBA can add a statement to a package on behalf of the owner (creator) of the module, where the owner is not authorized for the added function, the DBA should grant the proper authorization to the owner.

Examples

Example of Basic Extended PREPARE

PREPARE FROM :XSTRING SETTING :STMID
        IN :USERID.:PACKNAME USING DESCRIPTOR MYSQLDA

Example of Single Row Extended PREPARE

PREPARE SINGLE ROW FROM :XSTRING SETTING :STMID
        IN :USERID.:PACKNAME USING DESCRIPTOR MYSQLDA

Example of Empty Extended PREPARE

PREPARE FROM NULL SETTING :STMID
        IN :USERID.:PACKNAME

Example of Temporary Extended PREPARE

PREPARE FROM :XSTRING FOR :STMID
        IN :USERID.:PACKNAME

PUT

The PUT statement inserts a row into a table. It is most often used when blocking is in effect in order to create a block of rows to be inserted into a table at one time and thus improve performance.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared.

Authorization

For an explanation of the authorization required to use a cursor, see DECLARE CURSOR.

Syntax



>>-PUT--cursor_name----+------------------------------------+--><
                       +-FROM----host_variable_list---------+
                       '-USING DESCRIPTOR--descriptor_name--'
 

Description

cursor_name
Is an ordinary identifier that identifies the insert cursor to be used in the PUT operation. The cursor_name must identify a declared cursor as explained in DECLARE CURSOR. When the PUT statement is processed, the cursor must be in the open state.

FROM
This is only used in a PUT statement that is used in conjunction with a dynamic INSERT statement, in which case either FROM or USING DESCRIPTOR is required.

Introduces a list of host variables, host structure, or both, whose values are substituted for the parameter markers (question marks) in the dynamically-prepared INSERT statement. (For an explanation of parameter markers, see PREPARE.)

host_variable_list
Identifies a list of host variables, host structures, or both, that must be declared in the program in accordance with the rules for declaring host variables and host structures.

The total number of host variables and host structure subfields must be the same as the number of parameter markers in the prepared statement. The nth variable or subfield corresponds to the nth parameter marker in the prepared statement.

USING DESCRIPTOR descriptor_name
This is only used in a PUT statement that is used in conjunction with a dynamic INSERT statement, in which case either FROM or USING DESCRIPTOR is required.

Identifies an input SQLDA structure that provides information concerning input variables that were specified as parameter markers (?) when the INSERT statement was prepared.

Before the PUT statement is processed, the user must set the fields in the SQLDA described in the "Description" section of EXECUTE and Table 20.

Notes

When blocking is used, every time a PUT statement is processed, a single row of data is added to an insert-block. Rows are not inserted into the database until the block is full, or, until a CLOSE statement is processed. The PUT statement can also be processed when blocking is not in effect. In this case, one data row is inserted directly into a table.

Insert blocking is not available with the DRDA protocol.

The database manager does not notify your program of an insert error until the PUT that fills a block is processed. To determine when (or if) rows are actually inserted into the database, your program should examine SQLERRD(3) in the SQLCA when doing PUTs.

For example, suppose that 10 data rows to be inserted fit into one block, and that the data for the fourth insert is in error. PUTs 1 through 9 have successful SQLCA notifications, even though the insert for the fourth PUT has an error. On the tenth PUT, the block is full. The database manager tries to process the block of ten inserts, but encounters the error in the fourth row. It stops processing the block - that is, three rows are inserted successfully. SQLERRD(3) contains the number of rows that were successfully inserted. In this case, it contains a value of 3. If all rows were inserted successfully, it would contain 10. You can use SQLERRD(3) to determine where the error occurred.

Examples

Example 1

This example of statements from a PL/I program illustrates the use of a PUT statement with a static INSERT statement. The host variables EMPNO, FIRSTNME, MIDINIT, LASTNAME and EDLEVEL are compatible with the columns by the same name in the EMPLOYEE table. In this program, cursor PUTCUR inserts blocks of skeleton rows into the EMPLOYEE table.

  EXEC SQL  DECLARE PUTCUR CURSOR FOR
              INSERT INTO EMPLOYEE  (EMPNO, FIRSTNME, MIDINIT, LASTNAME, EDLEVEL)
                VALUES (:EMPNO, :FIRSTNME, :MIDINIT, :LASTNAME, :EDLEVEL);
 
  EXEC SQL  OPEN PUTCUR;
 
  ... /* code to start a loop */
    ... /* code to pick up values and assign them to host variables */
    EXEC SQL  PUT PUTCUR;
  ... /* code to end a loop */
 
 
  EXEC SQL  CLOSE PUTCUR;

Example 2

Similar to example 1, except that it uses a PUT statement with a dynamic INSERT statement.

  EXEC SQL  PREPARE INSERT_STMT FROM
               'INSERT INTO EMPLOYEE  (EMPNO, FIRSTNME, MIDINIT, LASTNAME, EDLEVEL)
                VALUES (? ? ? ? ?)';
 
  EXEC SQL  DECLARE PUTCUR CURSOR FORINSERT_STMT;
 
  EXEC SQL  OPEN PUTCUR;
 
  ... /* code to start a loop */
    ... /* code to pick up values and assign them to host variables  */
        /* and to the three subfields FIRSTNME, MIDINIT, LASTNAME    */
        /* of host structure EMPNAME.                                */
    EXEC SQL  PUT PUTCUR FROM :EMPNO, :EMPNAME, :EDLEVEL;
  ... /* code to end a loop */
 
  EXEC SQL  CLOSE PUTCUR;

Extended PUT

The Extended PUT statement inserts a row into a table. It is most often used when blocking is in effect in order to create a block of rows to be inserted into a table at one time and thus improve performance. The cursor must have been opened with an Extended OPEN.

Invocation

This statement can only be embedded in an application program written in Assembler or REXX.

Authorization

The authorization ID of the statement must have one of the following:

Syntax



>>-PUT--cursor_variable----------------------------------------->
 
>-----+------------------------------------+-------------------><
      |       .-,----------------.         |
      |       V                  |         |
      +-FROM-----host_variable---+---------+
      '-USING DESCRIPTOR--descriptor_name--'
 

Description

cursor_variable
Identifies the insert cursor that is to be used. The cursor must have been defined by a preceding Extended DECLARE CURSOR statement in the same logical unit of work.

FROM host_variable,...
Identifies variables in the program that will be used to provide the values that are to be inserted with the Extended PUT. The number of variables must be the same as the number of parameter markers in the prepared statement. The nth variable corresponds to the nth parameter marker in the prepared statement.

USING DESCRIPTOR descriptor_name
Identifies an input SQLDA structure that provides information concerning input variables that were specified as parameter markers (?) when the statement was prepared.

Before the Extended PUT statement is processed, the user must set the fields in the SQLDA described in the "Description" section of EXECUTE and Table 20.

The indicated cursor must be declared and opened.

Notes

In most respects, the Extended PUT statement is identical to the PUT statement (see PUT); however, in the Extended PUT statement, the cursor_variable is a host variable. This feature makes it possible for a user to provide the cursor name when the program is run and to enter a PUT statement in a logical unit of work or program other than the one in which the statement was prepared. Extended DECLARE CURSOR, OPEN, and PUT must occur in the same logical unit of work.

Examples

PUT :CURSOR1 FROM :X, :Y
 
PUT :CURSOR2 USING DESCRIPTOR SQLDA

REVOKE (Package Privileges)

This form of the REVOKE statement revokes the privilege to process statements in a package.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

This authorization ID must previously have granted the specified privileges to every authorization_name (or PUBLIC) specified in the FROM clause.

Note that someone with DBA authority can indirectly revoke the EXECUTE privilege on a package by obtaining the owner's password from the SYSTEM.SYSUSERAUTH catalog table and then connecting as the owner.

Syntax



                   (1)
>>-REVOKE EXECUTE--------ON--package_name----------------------->
 
           .-,-----------------------.
           V                         |
>----FROM----+-authorization_name-+--+-------------------------><
             |        (2)         |
             '-PUBLIC-------------'
 


Notes:



  1. RUN can be used as a synonym for EXECUTE and is provided for compatibility
    with previous versions of SQL/DS.

  2. PUBLIC is specified only once.


Description

EXECUTE ON package_name
Identifies the package from which the EXECUTE privilege is being removed. The package_name must identify a package that exists at the application server.

FROM authorization_name,...
Identifies the user from whom the privilege is revoked. authorization_name,... is a list of one or more authorization IDs. Do not use the same authorization_name more than once.

You cannot use the authorization_name of the REVOKE statement itself. (You cannot revoke privileges from yourself.)

PUBLIC
Revokes the privilege from PUBLIC.

Example

All users currently have the right to process the TREMAR package. PAYROLL, HANNA, and TREVOR have explicitly been granted this privilege. The other users have it because a GRANT EXECUTE TO PUBLIC statement was previously processed.

Remove the right to process the package from all users but PAYROLL.

  REVOKE EXECUTE ON TREMAR FROM HANNA, PUBLIC, TREVOR

REVOKE (System Authorities)

This form of the REVOKE statement allows a user having DBA authority to revoke authorities from other users.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

The authorization ID of the statement must have DBA authority.

Syntax



>>-REVOKE------------------------------------------------------->
 
                      .-,-----------------------.
                      V                         |
>-----+-CONNECT FROM----+-authorization_name-+--+-------+------><
      |                 |          (1)       |          |
      |                 '-ALLUSERS-----------'          |
      |                       .-,---------------------. |
      |                       V                       | |
      +--+-DBA------+---FROM-----authorization_name---+-+
      |  '-RESOURCE-'                                   |
      '-SCHEDULE FROM--subsystemid----------------------'
 


Notes:



  1. ALLUSERS can only be specified once.


Description

CONNECT
Revokes CONNECT authority from the specified authorization_names. Revoking CONNECT causes all authorities to be revoked with it and the authorization_name to be deleted from the catalog SYSUSERAUTH.

Revoking CONNECT does not cause objects owned by that authorization_name to be dropped. Neither does it cause table privileges for that authorization_name to be revoked. A user with DBA authority can later drop the objects and revoke the privileges.

DBA
Revokes DBA authority from the specified authorization_names. A user having DBA authority cannot revoke any authority from himself or herself. Revoking DBA authority automatically causes all authorities to be revoked except CONNECT.

RESOURCE
Revokes RESOURCE authority from the specified authorization_names. No one can revoke RESOURCE authority from a user that has DBA authority. Revoking RESOURCE authority implies no other revocations.

FROM
Introduces a list of one or more authorization_names.

authorization_name
An authorization ID.

ALLUSERS
Specifies that implicit CONNECT authority is to be revoked for all system-defined users.
VSE Users

ALLUSERS is not a valid option because implicit CONNECT authority is not applicable to VSE application servers.

SCHEDULE
Allows the DBA to revoke access by a CICS subsystem. Used with the VSE Guest sharing facility of the DB2 Server for VM product. For more information see the DB2 Server for VM System Administration or the DB2 Server for VSE System Administration manual.

FROM subsystemid
Is the subsystem ID of the CICS subsystem running under the VSE guest.

Note

If you enter REVOKE for an authority that the user does not have, the revocation is ignored for that authority.

Examples

Example 1

Given that VEILLEUX, MARINA, and HEARST have DBA authority, enter the statements necessary to revoke all authority from VEILLEUX. Leave MARINA with only CONNECT authority and leave HEARST with both CONNECT and RESOURCE authority.

  REVOKE DBA FROM VEILLEUX, MARINA, HEARST
 
  REVOKE CONNECT FROM VEILLEUX
 
  GRANT RESOURCE TO HEARST

Example 2

All users have previously been granted implicit connect authority from their VM user ID. PAYROLL, HANNA, and TREVOR have explicitly been granted this authority. The other users have it because a GRANT CONNECT TO ALLUSERS statement was previously processed.

Remove implicit connect authority from all users but PAYROLL.

  REVOKE CONNECT FROM HANNA, TREVOR, ALLUSERS
VSE Users

Example 2 does not apply to VSE.

REVOKE (Table Privileges)

This form of the REVOKE statement revokes privileges on the table or view.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that can be dynamically prepared.

Authorization

This authorization ID must previously have granted the specified privileges to every authorization_name (or PUBLIC) specified in the FROM clause.

Note that someone with DBA authority can indirectly revoke privileges on a table or view by obtaining the owner's password from the SYSTEM.SYSUSERAUTH catalog table and then connecting as the owner.

Syntax



                    .-PRIVILEGES-.
>>-REVOKE----+-ALL--+------------+-------+--ON------------------>
             |  .-,--------------------. |
             |  V         (1)          | |
             '----+-ALTER-----------+--+-'
                  +-DELETE----------+
                  |       (1)       |
                  +-INDEX-----------+
                  +-INSERT----------+
                  |            (1)  |
                  +-REFERENCES------+
                  +-SELECT----------+
                  '-UPDATE----------'
 
                            .-,-----------------------.
                            V                         |
>-----+-table_name-+--FROM----+-authorization_name-+--+--------><
      '-view_name--'          |        (2)         |
                              '-PUBLIC-------------'
 


Notes:



  1. The ALTER, INDEX, and REFERENCES options are not applicable to
    views.

  2. PUBLIC may only be specified once per statement.


Description

ALL  or  ALL PRIVILEGES
Revokes table privileges on the table or view identified in the ON clause. The privileges revoked are those possessed by the authorization ID of the REVOKE statement. ALL PRIVILEGES is the default.

ALTER
Revokes the privilege to use the ALTER TABLE statement. This privilege does not apply to views.

DELETE
Revokes the privilege to use the DELETE statement.

INDEX
Revokes the privilege to use the CREATE INDEX statement. This privilege does not apply to views.

INSERT
Revokes the privilege to use the INSERT statement.

REFERENCES
Revokes the privilege to either create referential constraints or to change existing referential constraints. This privilege does not apply to views.

SELECT
Revokes the privilege to use the SELECT statement or the CREATE VIEW statement.

UPDATE
Revokes the privilege to use the UPDATE statement. Note that a list of column names can be used only with GRANT, not with REVOKE. You must therefore revoke UPDATE on all columns.

ON table_name

ON view_name
Identifies the table or view from which the privileges are being revoked. The table_name or view_name must identify a table or view that exists at the application server.

FROM authorization_name,...
Identifies from whom the privileges are revoked. authorization_name,... is a list of one or more authorization IDs.

You cannot use the authorization_name of the REVOKE statement itself. (You cannot revoke privileges from yourself.)

PUBLIC
Revokes a grant of privileges to PUBLIC.

Dependent Privileges

When a privilege is revoked from a user, every privilege dependent on that privilege is also revoked.

A privilege P2 possessed by user U2 is dependent on privilege P1 possessed by user U1 if all of these are true:

Also, table privilege P2 is dependent on table privilege P1 if P2 was derived from P1 as a result of a CREATE VIEW statement.

Revoking a privilege that was used to create a package invalidates the package.

Multiple Grants

If you granted the same privilege to the same user more than once, revoking that privilege from that user negates all those grants. It does not negate any grant of that privilege made by others.

If a user has more than one source for a privilege, that privilege is not revoked until it is revoked by all sources (see example 2 below).

Note

The only way to revoke the WITH GRANT OPTION is to revoke the privilege itself and then to grant it again without the WITH GRANT OPTION.

Examples

Example 1

This example shows the effect of revoking a privilege that has a dependent privilege. To illustrate this process, the diagram that follows shows a sequence of GRANT and REVOKE statements.

                 *------------------------*
                 | Database Administrator |
                 *--------*-------*-------*
                         1GW     3R
                          V       V
                         *---------*
                         | PAULINE |
                         *----*----*
                             2G
                              V
                         *---------*
                         |  DAVE   |
                         *---------*

The statements illustrated in the above diagram are:

  1GW) from DBA:        GRANT SELECT ON TBLA TO PAULINE WITH GRANT OPTION
 
  2G)  from PAULINE:    GRANT SELECT ON TBLA TO DAVE
 
  3R)  from DBA:        REVOKE SELECT ON TBLA FROM PAULINE

Following this sequence of statements neither PAULINE nor DAVE has the SELECT privilege on TBLA. The explicit revoking of PAULINE's privilege implicitly revokes DAVE's as well.

Example 2

This extends example 1 in order to show the effect of having received a privilege from more than one source.

             *--------------------------------*
             |     Database Administrator     |
             *-*-------*----------------*-----*
              1GW     7R               2GW
               V       V                V
              *------------*      *------------*
              | PAULINE    |      |   SIMON    |
              *----------*-*      *-*----------*
                        3GW        5GW
                         V          V
                        *------------*
                        |    DAVE    |
                        **----------**
                        4G         6G
                         V          V
              *------------*      *------------*
              |    JAY     |      |  RICHARD   |
              *------------*      *------------*

Following this sequence of statements from the users indicated:

  1GW) from DBA:        GRANT SELECT ON TBLA TO PAULINE WITH GRANT OPTION
 
  2GW) from DBA:        GRANT SELECT ON TBLA TO SIMON   WITH GRANT OPTION
 
  3GW) from PAULINE     GRANT SELECT ON TBLA TO DAVE    WITH GRANT OPTION
 
  4G)  from DAVE:       GRANT SELECT ON TBLA TO JAY
 
  5GW  from SIMON:      GRANT SELECT ON TBLA TO DAVE    WITH GRANT OPTION
 
  6G)  from DAVE:       GRANT SELECT ON TBLA TO RICHARD
 
  7R)  from Admin:      REVOKE SELECT ON TBLA FROM PAULINE

PAULINE loses her SELECT privilege on TBLA, but DAVE retains his (having obtained it from SIMON as well).

JAY loses his SELECT privilege because he obtained it from DAVE at a time when DAVE had only obtained the SELECT WITH GRANT privilege from PAULINE.

RICHARD retains his SELECT privilege because he obtained it from DAVE at a time when DAVE had obtained the SELECT WITH GRANT privilege from both PAULINE and SIMON.

Example 3

This example shows how the revocation of a PUBLIC privilege varies depending on whether: that privilege was granted specifically to that user or that privilege was obtained using a GRANT TO PUBLIC.

             *--------------------------------*
             |     Database Administrator     |
             *-*------------*---------------*-*
              1GW          2GP             4RP
               V            |               |
              *---------*   |               |
              | MARY    |   |               |
              *-------*-*   |               |
                     3G     *---------*     |
                      V     V         V     V
                    *---------*     *--------------------------*
                    | RICHARD |     | LOUIS (and other public) |
                    *---------*     *--------------------------*

Following this sequence of statements from the users indicated:

  1GW) from DBA:         GRANT SELECT ON TBLA TO MARY WITH GRANT OPTION
 
  2GP) from DBA:         GRANT SELECT ON TBLA TO PUBLIC
 
  3G)  from MARY:        GRANT SELECT ON TBLA TO RICHARD
 
  4RP) from DBA:         REVOKE SELECT ON TBLA FROM PUBLIC

RICHARD retains the SELECT privilege on TBLA even though he was originally granted it as a member of the public. LOUIS only had the SELECT privilege as a member of the public, so loses that privilege.

ROLLBACK

The ROLLBACK statement ends a logical unit of work and back out the database changes that were made by that logical unit of work.

Invocation

This statement can be embedded in an application program or issued interactively. It is an executable statement that cannot be dynamically prepared.

Authorization

None required.

Syntax



             .-WORK-.
>>-ROLLBACK--+------+--+---------+-----------------------------><
                       '-RELEASE-'
 

Description

RELEASE
Re-establishes the default user ID and default database

for a subsequent logical unit of work. If this default user ID had been overridden with an explicit CONNECT, in the terminating logical unit of work that explicitly established user ID is replaced by the default user ID. By not specifying RELEASE, the user ID and database at termination of the logical unit of work are retained for a subsequent logical unit of work. For VSE interactive users connected to a remote DRDA application server, when the next SQL statement is entered, you are automatically connected with your CICS signon user ID to the same application server.

ROLLBACK terminates the logical unit of work in which ROLLBACK is processed. All changes made by the following statements during a logical unit of work, are backed out:



ACQUIRE DBSPACE
ALTER DBSPACE
ALTER PROCEDURE
ALTER PSERVER
ALTER TABLE
COMMENT ON
CREATE INDEX
CREATE PROCEDURE
CREATE PSERVER
CREATE SYNONYM
CREATE TABLE
CREATE VIEW
DELETE
DROP
DROP PROCEDURE
DROP PSERVER
EXPLAIN
GRANT Package Privileges
GRANT System Authorities
GRANT Table/View Privileges
INSERT
LABEL ON
PUT
REVOKE Package Privileges
REVOKE System Authorities
REVOKE Table/View Privileges
UPDATE
UPDATE STATISTICS

All locks acquired by the logical unit of work are released.

All cursors that were opened during the logical unit of work are closed. All statements that were prepared during the logical unit of work are destroyed. Any cursors associated with a prepared statement that is destroyed cannot be opened until the statement is prepared again.

Notes

If a COMMIT or ROLLBACK does not immediately precede the termination of an application process, the database manager attempts to commit the work (it may, however, not always be successful). It is strongly recommended that each application process explicitly ends its logical unit of work before terminating.

ROLLBACK should not be issued after a severe error has occurred (one which sets the SQLWARN0 field in the SQLCA to 'S'). In this situation, the only statement that can be issued is a CONNECT statement to another application server.

|The logical unit of work must be completed by using the COMMIT or |ROLLBACK statements before the CONNECT statement can be used to switch to |another user ID or application server.

|TCP/IP does not perform any security checking during a physical |connect. The Batch application requester will use the DRDA security |handshaking flows during the logical connect to perform user ID and password |verification. The physical TCP/IP connection will be deallocated and |reallocated whenever the application switches to a different user ID or server |name (using the CONNECT statement), and DRDA security handshaking flows will |be used again during the logical connect. Either of these switches will |not require the application to issue a COMMIT RELEASE or ROLLBACK |RELEASE. The Batch Resource Adapter will retain and use the current |user ID, password, and server name (unless different ones are specified with a |new CONNECT statement) after the new TCP/IP physical connection is |established. If a COMMIT RELEASE or ROLLBACK RELEASE was issued prior |to a CONNECT statement, then all user ID, password and server name information |is lost and must be supplied with the next CONNECT.

Examples

The PL/I program in COMMIT illustrates how the ROLLBACK statement is used.

SELECT INTO

The SELECT INTO statement produces a result table consisting of at most one row, and assigns the values in that row to host variables. If the table is empty, the statement assigns +100 to SQLCODE and '02000' to SQLSTATE and does not assign values to the host variables. If more than one row satisfies the search condition, statement processing is terminated and an error occurs.

Invocation

This statement can only be embedded in an application program. It is an executable statement that cannot be dynamically prepared.

In FORTRAN, REXX, and programs prepared using extended dynamic SQL, SELECT INTO cannot be used with the DRDA protocol.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

Syntax



>>-select_clause--INTO------host_variable_list------------------>
 
>----from_clause--+--------------+----+-------------+----------><
                  '-where_clause-'    '-with_clause-'
 

Description

The result table is derived by evaluating the from_clause, where_clause, and select_clause, in this order.

See Chapter 5, Queries for a description of the select_clause, from_clause, and where_clause.

INTO
Introduces a list of host variables, host structures, or both.

host_variable_list
Identifies a list of host variables, host structures, or both, that must be declared in the program in accordance with the rules for declaring host variables and host structures.

The first value in the result row is assigned to the first host_variable or host structure subfield in the list, the second value to the second variable, and so on. If the number of host variables and host structure subfields is less than the number of select_list values, the value W is assigned to the SQLWARN3 field of the SQLCA. (See SQL Communication Area (SQLCA).) Note that there is no warning if there are more variables than the number of select_list values. For a datetime value, the variable must be a character string variable of a minimum length as defined in Chapter 3, "Language Elements".

If the value is null, an indicator variable must be specified.

Each assignment to a variable is made according to the rules described in Chapter 3, "Language Elements".



>>-WITH----+-RR-+----------------------------------------------><
           +-CS-+
           '-UR-'
 

WITH
Specifies the isolation level at which the statement is executed.

RR
Repeatable read

CS
Cursor stability

UR
Uncommitted read

If an error occurs, no value is assigned to the host variable or to variables later in the list, though any values that have already been assigned to variables remain assigned.

If an error occurs because the result table has more than one row, values may or may not be assigned to the host variables. If values are assigned to the host variables, the row that is the source of the values is undefined and not predictable.

See the DB2 Server for VSE & VM Application Programming manual for a description of the possible errors when SELECT INTO is processed.

Examples

Example 1

Using a COBOL program statement, put the maximum salary (SALARY) from the EMPLOYEE table into the host variable MAX-SALARY (dec(9,2)).

  EXEC SQL  SELECT MAX(SALARY)
              INTO :MAX-SALARY
              FROM EMPLOYEE
  END-EXEC.

Example 2

Using a PL/I program statement, select the row from the EMPLOYEE table with a employee number (EMPNO) value the same as that stored in the host variable HOST_EMP char(6)). Then put the first name (FIRSTNME) and last name (LASTNAME) into the host structure HOST_NAME, and education level (EDLEVEL) into the host variable HOST_EDUCATE (integer) from that row.

  EXEC SQL  SELECT FIRSTNME, LASTNAME, EDLEVEL
              INTO :HOST_NAME, :HOST_EDUCATE
              FROM EMPLOYEE
              WHERE EMPNO = :HOST_EMP;

UPDATE

The UPDATE statement updates the values of specified columns in rows of a table or view. Updating a row of a view updates a row of its base table.

There are two forms of this statement:

Invocation

A Searched UPDATE statement can be embedded in an application program or issued interactively. A Positioned UPDATE must be embedded in an application program. Both Searched UPDATE and Positioned UPDATE are executable statements that can be dynamically prepared.

A Positioned UPDATE in FORTRAN, and programs prepared using extended dynamic SQL cannot be used with the DRDA protocol.

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

The UPDATE privilege on a view is only inherent in DBA authority. Ownership of a view does not necessarily include the UPDATE privilege on the view because the privilege may not have been granted when the view was created, or it may have been granted, but subsequently revoked.

If the search_condition includes a subquery, the privileges designated by the authorization ID of the statement must also include at least one of the following:

Syntax



Searched UPDATE:

>>-UPDATE----+-table_name-+--+------------------+--------------->
             '-view_name--'  '-correlation_name-'
 
           .-,----------------------------------.
           V                                    |
>-----SET-----column_name-- = --+-expression-+--+--------------->
                                '-NULL-------'
 
>-----+--------------------------+---+---------------+---------><
      '-WHERE--search_condition--'   '-WITH--+-RR-+--'
                                             '-CS-'
 

Positioned UPDATE:

>>-UPDATE----+-table_name-+------------------------------------->
             '-view_name--'
 
           .-,----------------------------------.
           V                                    |
>-----SET-----column_name-- = --+-expression-+--+--------------->
                                '-NULL-------'
 
>----WHERE CURRENT OF--cursor_name-----------------------------><
 

Description

table_name  or  view_name
Identifies the table or view to be updated. The name must identify a table or view that exists at the application server, but must not identify a catalog table, a view of a catalog table, or a read-only view. For an explanation of read-only views, see CREATE VIEW.
Note: Someone with DBA authority may update rows from a few of the catalog tables. See Updateable Columns.

correlation_name
Can be used within search_condition to designate the table or view. (For an explanation of correlation_name, see Correlation Names.)

SET
Introduces a list of column names and values.

column_name
Identifies a column to be updated. The column_name must identify a column of the specified table or view, but must not identify a view column derived from a scalar function, constant, or expression. The column names must not be qualified, and a column must not be specified more than once.

For a Positioned UPDATE, allowable column names can be further restricted to those in a certain list. This list appears in the UPDATE clause of the select statement for the associated cursor. The column names need not be in the select-list of the select statement for the associated cursor If the select statement is dynamically prepared, the UPDATE clause must always be present. Otherwise, the clause can be omitted under the conditions described in The NOFOR Option.

A view column derived from the same column as another column of the view can be updated, but both columns cannot be updated in the same UPDATE statement.

expression  or  NULL
Indicates the new value of the column. The expression is any expression of the type described in Chapter 3, "Language Elements". It must not include a column function. NULL specifies the null value.

A column_name in an expression must name a column of the named table or view. For each row that is updated, the value of the column in the expression is the value of the column in the row before the row is updated.

If the column_name on the left hand side of the SET identifies a long string column, the only type of expression allowed is a host-variable.

WHERE
Specifies the rows to be updated. You can omit the clause, give a search condition, or name a cursor. If the clause is omitted, all rows of the table or view are updated.

search_condition
Is any search condition described in Chapter 3, "Language Elements". Each column_name in the search condition, other than in a subquery, must name a column of the table or view. The search condition must not include a subquery where the base object of both the UPDATE and the subquery is the same table.

The search_condition is applied to each row of the table or view and the updated rows are those for which the result of the search_condition is true.

If the search condition contains a subquery, the subquery can be thought of as being processed each time the search condition is applied to a row, and the results used in applying the search condition. In actuality, the subquery is processed for each row only if it contains a correlated reference to a column of the table or view.

WITH
Specifies the isloation level used when locating the rows to be updated by the statement.

RR
Repeatable read

CS
Cursor stability

The default isolation level of the statement is the isolation level of the package. WITH can only be specified on a SEARCHED update; it is incompatible with the WHERE CURRENT OF clause.

CURRENT OF cursor_name
Identifies the cursor to be used in the update operation. The cursor_name must identify a declared cursor as explained in DECLARE CURSOR. The cursor_name can be a delimited identifier. If cursor_name is a reserved word, it must be a delimited identifier.

The table or view specified must also be identified in the FROM clause of the select-statement of the cursor, and the result table of the cursor must not be read-only. (For an explanation of read-only result tables, see DECLARE CURSOR.)

When the UPDATE statement is processed, the cursor must be positioned on a row and that row is updated.

Update values must satisfy the following rules. If they do not, or if any other errors occur during the execution of the UPDATE statement, no rows are updated.

When an UPDATE statement completes execution, the value of SQLERRD(3) in the SQLCA is the number of rows updated. (For a description of the SQLCA, see SQL Communication Area (SQLCA).)

Differences Between Searched Updates in Recoverable and Non-Recoverable Storage Pools

Recoverable Storage Pool

Uniqueness is checked after all rows are updated.

Non-Recoverable Storage Pool

When multiple-row updates are performed against a column that has a unique index, the database manager is sensitive to the order (ascending or descending) of the data. Since the database manager automatically creates a unique index on a primary key column, a Searched UPDATE cannot be used to perform multiple-row updates against the primary key column. This is to ensure that updates to the primary key are independent of the order of the data. For the same reason, a Positioned UPDATE cannot be used to update primary key columns.

Locking

Unless appropriate locks already exist, one or more exclusive locks are acquired by the execution of a successful UPDATE statement. Until the locks are released, the updated row can only be accessed by the application process that performed the update. For further information on locking, see the descriptions of the COMMIT, ROLLBACK, LOCK TABLE, and LOCK DBSPACE statements.

Blocking

The blocking options, SBLocK or BLocK, in the SQLPREP command and the CREATE PACKAGE statement improves performance as they insert and retrieve rows in groups. However, if a program was preprocessed with the NOFOR option, query cursors referenced in Positioned UPDATE statements are unavailable for blocking. If a Positioned UPDATE is coded in a program and NOFOR is not in effect, then a FOR UPDATE OF clause must be included in the select-statement. See the DB2 Server for VSE & VM Application Programming manual for more information on blocking when preprocessing and running a program.

Error Conditions

It is possible for an error to occur that makes the state of the cursor unpredictable. If an error occurs during the execution of a Positioned UPDATE that makes the position of a cursor unpredictable, the cursor is closed.

If an error occurs during the execution of a Searched UPDATE, you must inspect SQLWARN6 to determine the extent of the error. The following are the current settings of SQLWARN6 along with possible responses:

  1. SQLWARN6 is set to 'S'. A severe error has occurred, leaving the system in an unusable state.
  2. SQLWARN6 is set to 'W'. An error occurred causing the LUW to be rolled back automatically. The system is still in a usable state. The application can:
  3. SQLWARN6 is blank. An error has occurred, but the LUW is still active. Any changes made by the request have been rolled back, hence the failing request has not left any partial results in the database. The application can:

Examples

Example 1

Change the job (JOB) of employee number (EMPNO) '000290' in the EMPLOYEE table to 'LABORER'.

  UPDATE EMPLOYEE
    SET JOB = 'LABORER'
    WHERE EMPNO = '000290'

Example 2

Increase the project staffing (PRSTAFF) by 1.5 for all projects that department (DEPTNO) 'D21' is responsible for in the PROJECT table.

  UPDATE PROJECT
    SET PRSTAFF = PRSTAFF + 1.5
    WHERE DEPTNO = 'D21'

Example 3

All the employees except the manager of department (WORKDEPT) 'E21' have been temporarily laid off. Indicate this by changing their job (JOB) to NULL and their pay (SALARY, BONUS, COMM) values to zero in the EMPLOYEE table.

  UPDATE EMPLOYEE
    SET JOB=NULL, SALARY=0, BONUS=0, COMM=0
    WHERE DEPTNO = 'E21'
    AND JOB <> 'MANAGER'

Example 4

In a PL/I program display the rows from the EMPLOYEE table and then, if requested to do so, change the job (JOB) of certain employees to the new job keyed in.

  EXEC SQL  DECLARE C1 CURSOR FOR
              SELECT *
                FROM EMPLOYEE
                FOR UPDATE OF JOB;
 
  EXEC SQL  OPEN C1;
 
  EXEC SQL  FETCH C1 INTO ...     ;
 
  PUT ...      ;
  GET LIST (CHANGE, NEWJOB);
  IF CHANGE = 'YES' THEN
    EXEC SQL  UPDATE EMPLOYEE
                SET JOB = :NEWJOB
                WHERE CURRENT OF C1;
 
  EXEC SQL  CLOSE C1;

UPDATE STATISTICS

The UPDATE STATISTICS statement causes internal statistics of tables and indexes to be updated with current information.

Invocation

This statement can be embedded in an application program, or it can be issued interactively.

Authorization

The privileges held by the authorization ID of the statement must include CONNECT authority.

Syntax



>>-UPDATE--+-----+--STATISTICS FOR------------------------------>
           '-ALL-'
 
>-----+-TABLE--table_name------+-------------------------------><
      '-DBSPACE--dbspace_name--'
 

Description

Invoking UPDATE STATISTICS can improve performance on statements that access data from tables. These statistics, contained in the catalog tables, include the table size, various index characteristics, and other information.

ALL
Updates statistics for all columns. In the case of a column which is not a first column of any index, the column statistics are an approximation. If ALL is not specified, statistics are only updated for a column which is the first column of any index.

FOR TABLE
Indicates the table for which you want the statistics updated. If the table name is qualified, the qualifier is the owner of the table. Otherwise, the authorization ID of the statement is the owner of the table.

table_name
Identifies the table whose statistics you want updated. The name must identify a base table that exists at the application server.

FOR DBSPACE
Updates the statistics for all tables in the designated dbspace. If the dbspace name is qualified, the qualifier is the owner of the dbspace. Otherwise, the authorization ID of the statement is the owner of the dbspace.

dbspace_name
Identifies the dbspace containing the tables whose statistics you want updated. The name must identify a dbspace that exists at the application server.

Examples

This shows the statements that are embedded in a PL/I program in order to add an index on project name (PROJNAME) to the PROJECT table and to update the statistics on that table. This is so that programs using that table that are subsequently reprepared can consider those statistics when determining an access strategy.

  EXEC SQL  CREATE INDEX PROJNAME
              ON PROJECT(PROJNAME);
 
  EXEC SQL  UPDATE STATISTICS FOR TABLE PROJECT;

WHENEVER

The WHENEVER statement specifies the next host language statement to which execution will be transferred when a specified exception condition occurs.

Invocation

This statement can only be embedded in an application program. It is not an executable statement. It is not supported in REXX.

Authorization

None required.

Syntax



>>-WHENEVER----------------------------------------------------->
 
>-----+--+-SQLERROR---+---+-CONTINUE------------------------+-+-><
      |  '-SQLWARNING-'   |      (1)                        | |
      |                   +-STOP----------------------------+ |
      |                   '--+-GOTO--+---+---+--host_label--' |
      |                      '-GO TO-'   '-:-'                |
      '-NOT FOUND--+-CONTINUE------------------------+--------'
                   '--+-GOTO--+---+---+--host_label--'
                      '-GO TO-'   '-:-'
 


Notes:



  1. STOP is not valid for C, and FORTRAN.


Description

The SQLERROR, SQLWARNING or NOT FOUND, clause identifies the type of exception condition.

SQLERROR
Identifies any condition that results in a negative value in SQLCODE.

SQLWARNING
Identifies any condition that results in a warning condition (SQLWARN0 is 'W'), or that results in a positive value other than +100 in SQLCODE.

NOT FOUND
Identifies any condition that results in an SQLCODE of +100 and an SQLSTATE of '02000'.

The CONTINUE, GO TO, or STOP clause specifies the next statement to be processed when the identified type of exception condition exists.

CONTINUE
Causes the next sequential instruction of the source program to be processed.

GOTO host_label

GO TO host_label
Causes control to pass to the statement identified by host_label. For host_label, substitute a host identifier optionally preceded by a colon. The form of the host identifier depends on the host language. In COBOL, for example, it can be a section-name or an unqualified paragraph-name. In a FORTRAN program, it is an unsigned integer variable not preceded by a colon.

STOP
Causes program termination. If a logical unit of work is in progress, it is rolled back.

Notes

There are three types of WHENEVER statements:

WHENEVER SQLERROR
WHENEVER SQLWARNING
WHENEVER NOT FOUND

Every executable SQL statement in a program is within the scope of one implicit or explicit WHENEVER statement of each type. The scope of a WHENEVER statement is related to the listing sequence of the statements in the program, not their execution sequence.

An SQL statement is within the scope of the last WHENEVER statement of each type that is specified before that SQL statement in the source program. If a WHENEVER statement of some type is not specified before an SQL statement, that SQL statement is within the scope of an implicit WHENEVER statement of that type in which CONTINUE is specified.

Examples

Write the statements that need to be embedded in a COBOL program in order to:

  1. Go to the label HANDLER for any statement that produces an error
  2. Continue processing for any statement that produces a warning
  3. Go to the label ENDDATA for any statement that does not return data when expected to do so.

  EXEC SQL  WHENEVER SQLERROR GOTO HANDLER  END-EXEC.
  EXEC SQL  WHENEVER NOT FOUND GOTO ENDDATA  END-EXEC.


[ Top of Page | Previous Page | Next Page | Table of Contents | Index ]