SQL Reference

CREATE TYPE (Structured)

The CREATE TYPE statement defines a user-defined structured type. A user-defined structured type may include zero or more attributes. A structured type may be a subtype allowing attributes to be inherited from a supertype. Successful execution of the statement generates methods, for retrieving and updating values of attributes. Successful execution of the statement also generates functions, for constructing instances of a structured type used in a column, for casting between the reference type and its representation type, and for supporting the comparison operators (=, <>, <, <=, >, and >=) on the reference type.

The CREATE TYPE statement also defines any method specifications for user-defined methods to be used with the user-defined structured type.

Invocation

This statement can be embedded in an application program or issued through the use of dynamic SQL statements. It is an executable statement that can be dynamically prepared. However, if the bind option DYNAMICRULES BIND applies, the statement cannot be dynamically prepared (SQLSTATE 42509).

Authorization

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

If UNDER is specified and the authorization ID of the statement is not the same as the definer of the root type of the type hierarchy, then SYSADM or DBADM authority is required.

Syntax

>>-CREATE TYPE--type-name----+-------------------------+-------->
                             '-UNDER--supertype-name---'
 
>-----+---------------------------------------------+--*-------->
      |        .-,---------------------------.      |
      |        V                             |      |
      '-AS--(-----| attribute-definition |---+---)--'
 
      .-INSTANTIABLE-----.
>-----+------------------+--*---+-------------------------+--*-->
      '-NOT INSTANTIABLE-'      '-INLINE LENGTH--integer--'
 
     .-WITHOUT COMPARISONS-.       .-NOT FINAL-.
>----+---------------------+---*---+-----------+---*------------>
 
>----MODE DB2SQL---*----+-----------------------+--*------------>
                        '-WITH FUNCTION ACCESS--'
 
>-----+--------------------------+------------------------------>
      '-REF USING--| rep-type |--'
 
>----*--+---------------------------------------+--*------------>
        '-CAST (SOURCE AS REF) WITH--funcname1--'
 
>-----+----------------------------------------+--*------------->
      '-CAST (REF AS SOURCE) WITH--funcname2---'
 
>-----+----------------------------------+---------------------><
      |  .-,--------------------------.  |
      |  V                            |  |
      '----| method-specification |---+--'
 
attribute-definition
 
|---attribute-name--| data-type |----+----------------------+---|
                                     +-| lob-options |------+
                                     '-| datalink-options |-'
 
rep-type
 
|---+-SMALLINT-----------------------------------------------------------------------+->
    +-+-INTEGER-+--------------------------------------------------------------------+
    | '-INT-----'                                                                    |
    +-BIGINT-------------------------------------------------------------------------+
    +--+-DECIMAL-+---+----------------------------------+----------------------------+
    |  +-DEC-----+   '-(--integer--+-------------+---)--'                            |
    |  +-NUMERIC-+                 '-,--integer--'                                   |
    |  '-NUM-----'                                                                   |
    +--+--+-CHARACTER-+---+------------+----------------+---+----------------------+-+
    |  |  '-CHAR------'   '-(integer)--'                |   |  (1)                 | |
    |  '--+-VARCHAR-------------------+--(--integer--)--'   '--------FOR BIT DATA--' |
    |     '--+-CHARACTER-+---VARYING--'                                              |
    |        '-CHAR------'                                                           |
    |                                                                                |
    +-GRAPHIC--+------------+--------------------------------------------------------+
    |          '-(integer)--'                                                        |
    '-VARGRAPHIC--(--integer--)------------------------------------------------------'
 
>---------------------------------------------------------------|
 
method-specification
 
|---METHOD--method-name----------------------------------------->
 
>----(--+----------------------------------------------------------+---)->
        |  .-,--------------------------------------------------.  |
        |  V                                                    |  |
        '----+-----------------+---data-type2--+-------------+--+--'
             '-parameter-name--'               '-AS LOCATOR--'
 
>----*---RETURNS------------------------------------------------>
 
>-----+-data-type3--+-------------+------------------------+---->
      |             '-AS LOCATOR--'                        |
      '-data-type4--CAST FROM--data-type5--+-------------+-'
                                           '-AS LOCATOR--'
 
>----*----+--------------------------+--*----------------------->
          '-SPECIFIC--specific-name--'
 
>-----+-----------------+--*------------------------------------>
      '-SELF AS RESULT--'
 
      .-| SQL-routine-characteristics |-------.
>-----+---------------------------------------+--*--------------|
      '-| external-routine-characteristics |--'
 
SQL-routine-characteristics
 
        .-LANGUAGE SQL-.        .-NOT DETERMINISTIC--.
|---*---+--------------+---*----+--------------------+--*------->
                                '-DETERMINISTIC------'
 
      .-NO EXTERNAL ACTION--.       .-READS SQL DATA--.
>-----+---------------------+--*----+-----------------+--*------>
      '-EXTERNAL ACTION-----'       '-CONTAINS SQL----'
 
      .-CALLED ON NULL INPUT--.
>-----+-----------------------+--*------------------------------|
 
external-routine-characteristics
 
|---*---LANGUAGE--+-C----+--*---PARAMETER STYLE--+-DB2SQL-----+->
                  +-JAVA-+                       '-DB2GENERAL-'
                  '-OLE--'
 
          .-NOT DETERMINISTIC--.       .-FENCED-----.
>----*----+--------------------+--*----+------------+--*-------->
          |               (2)  |       '-NOT FENCED-'
          '-DETERMINISTIC------'
 
      .-CALLED ON NULL INPUT------------.
>-----+---------------------------------+--*---NO SQL---*------->
      |                            (3)  |
      '-RETURNS NULL ON NULL INPUT------'
 
      .-NO EXTERNAL ACTION--.       .-NO SCRATCHPAD----------.
>-----+---------------------+--*----+------------------------+-->
      '-EXTERNAL ACTION-----'       |             .-100----. |
                                    '-SCRATCHPAD--+--------+-'
                                                  '-length-'
 
          .-NO FINAL CALL--.       .-ALLOW PARALLEL----.
>----*----+----------------+--*----+-------------------+--*----->
          '-FINAL CALL-----'       '-DISALLOW PARALLEL-'
 
      .-NO DBINFO--.
>-----+------------+--*-----------------------------------------|
      '-DBINFO-----'
 

Notes:

  1. The FOR BIT DATA clause may be specified in random order with the other column constraints that follow.

  2. NOT VARIANT may be specified in place of DETERMINISTIC and VARIANT may be specified in place of NOT DETERMINISTIC.

  3. NULL CALL may be specified in place of CALLED ON NULL INPUT and NOT NULL CALL may be specified in place of RETURNS NULL ON NULL INPUT.

Description

type-name
Names the type. The name, including the implicit or explicit qualifier, must not identify any other type (built-in, structured, or distinct) already described in the catalog. The unqualified name must not be the same as the name of a built-in data type or BOOLEAN (SQLSTATE 42918). In dynamic SQL statements, the CURRENT SCHEMA special register is used as a qualifier for an unqualified object name. In static SQL statements the QUALIFIER precompile/bind option implicitly specifies the qualifier for unqualified object names.

The schema name (implicit or explicit) must not be greater than 8 bytes (SQLSTATE 42622).

A number of names used as keywords in predicates are reserved for system use, and cannot be used as a type-name (SQLSTATE 42939). The names are SOME, ANY, ALL, NOT, AND, OR, BETWEEN, NULL, LIKE, EXISTS, IN, UNIQUE, OVERLAPS, SIMILAR, MATCH and the comparison operators as described in Basic Predicate.

If a two-part type-name is specified, the schema name cannot begin with "SYS"; otherwise, an error (SQLSTATE 42939) is raised.

UNDER supertype-name
Specifies that this structured type is a subtype under the specified supertype-name. The supertype-name must identify an existing structured type (SQLSTATE 42704). If supertype-name is specified without a schema name, the type is resolved by searching the schemas on the SQL path. The structured type includes all the attributes of the supertype followed by the additional attributes given in the attribute-definition.

attribute-definition
Defines the attributes of the structured type.

attribute-name
The name of an attribute. The attribute-name cannot be the same as any other attribute of this structured type or any supertype of this structured type (SQLSTATE 42711).

A number of names used as keywords in predicates are reserved for system use, and cannot be used as an attribute-name (SQLSTATE 42939). The names are SOME, ANY, ALL, NOT, AND, OR, BETWEEN, NULL, LIKE, EXISTS, IN, UNIQUE, OVERLAPS, SIMILAR, MATCH and the comparison operators as described in Basic Predicate.

data-type
The data type of the attribute. It is one of the data types listed under CREATE TABLE other than LONG VARCHAR, LONG VARGRAPHIC, or a distinct type based on LONG VARCHAR or LONG VARGRAPHIC (SQLSTATE 42601). The data type must identify an existing data type (SQLSTATE 42704). If data-type is specified without a schema name, the type is resolved by searching the schemas on the SQL path. The description of various data types is given in CREATE TABLE. If the attribute data type is a reference type, the target type of the reference must be a structured type that exists, or is created by this statement (SQLSTATE 42704).

A structured type defined with an attribute of type DATALINK can only be effectively used as the data type for a typed table or typed view (SQLSTATE 01641).

To prevent type definitions that would, at runtime, permit an instance of the type to directly or indirectly contain another instance of the same type or one of its subtypes, a type can not be defined such that one of its attribute types directly or indirectly uses itself (SQLSTATE 428EP). See Structured Types for more information.

lob-options
Specifies the options associated with LOB types (or distinct types based on LOB types). For a detailed description of lob-options, see CREATE TABLE.

datalink-options
Specifies the options associated with DATALINK types (or distinct types based on DATALINK types). For a detailed description of datalink-options, see CREATE TABLE.

Note that if no options are specified for a DATALINK type or distinct type sourced on DATALINK, LINKTYPE URL and NO LINK CONTROL options are the defaults.

INSTANTIABLE or NOT INSTANTIABLE
Determines whether an instance of the structured type can be created. Implications of not instantiable structured types are:

To create instances of a non-instantiable type, instantiable subtypes must be created. If NOT INSTANTIABLE is specified, no instance of the new type can be created.

INLINE LENGTH integer
This option indicates the maximum size (in bytes) of a structured type column instance to store inline with the rest of the values in the row of a table. Instances of a structured type or its subtypes, that are larger than the specified inline length, are stored separately from the base table row, similar to the way that LOB values are handled.

If the specified INLINE LENGTH is smaller than the size of the result of the constructor function for the newly-created type (32 bytes plus 10 bytes per attribute) and smaller than 292 bytes, an error results (SQLSTATE 429B2). Note that the number of attributes includes all attributes inherited from the supertype of the type.

The INLINE LENGTH for the type, whether specified or a default value, is the default inline length for columns that use the structured type. This default can be overridden at CREATE TABLE time.

INLINE LENGTH has no meaning when the structured type is used as the type of a typed table.

The default INLINE LENGTH for a structured type is calculated by the system. In the formula given below, the following terms are used:

short attribute
refers to an attribute with any of the following data types: SMALLINT, INTEGER, BIGINT, REAL, DOUBLE, FLOAT, DATE, or TIME. Also included are distinct types or reference types based on these types.

non-short attribute
refers to an attribute of any of the remaining data types, or distinct types based on those data types.

The system calculates the default inline length as follows:

  1. Determine the added space requirements for non-short attributes using the following formula:

    space_for_non_short_attributes = SUM(attributelength + n)

    n is defined as:

    • 0 bytes for nested structured type attributes
    • 2 bytes for non-LOB attributes
    • 9 bytes for LOB attributes

    attributelength is based on the data type specified for the attribute as shown in Table 25.

  2. Calculate the total default inline length using the following formula:

    default_length(structured_type) = (number_of_attributes * 10) + 32 + space_for_non-short_attributes

    number_of_attributes is the total number of attributes for the structured type, including attributes that are inherited from its supertype. However, number_of_attributes does not include any attributes defined for any subtype of structured_type.


Table 25. Byte Counts for Attribute Data Types
Attribute Data Type Byte Count
DECIMAL The integral part of (p/2)+1, where p is the precision
CHAR(n) n
VARCHAR(n) n
GRAPHIC(n) n * 2
VARGRAPHIC(n) n * 2
TIMESTAMP 10
DATALINK(n) n + 54
LOB Type Each LOB attribute has a LOB descriptor in the structured type instance that points to the location of the actual value. The size of the descriptor varies according to the maximum length defined for the LOB attribute
Maximum LOB Length LOB Descriptor Size
1 024 72
8 192 96
65 536 120
524 000 144
4 190 000 168
134 000 000 200
536 000 000 224
1 070 000 000 256
1 470 000 000 280
2 147 483 647 316
Distinct Type Length of the source type of the distinct type
Reference Type Length of the built-in data type on which the reference type is based.
Structured Type inline_length(attribute_type)

WITHOUT COMPARISONS
Indicates that there are no comparison functions supported for instances of the structured type.

NOT FINAL
Indicates that the structured type may be used as a supertype.

MODE DB2SQL
This clause is required and allows for direct invocation of the constructor function on this type.

WITH FUNCTION ACCESS
Indicates that all methods of this type and its subtypes, including methods created in the future, can be accessed using functional notation. This clause can be specified only for the root type of a structured type hierarchy (the UNDER clause is not specified) (SQLSTATE 42613). This clause is provided to allow the use of functional notation for those applications that prefer this form of notation over method invocation notation.

REF USING rep-type
Defines the built-in data type used as the representation (underlying data type) for the reference type of this structured type and all its subtypes. This clause can only be specified for the root type of a structured type hierarchy (UNDER clause is not specified) (SQLSTATE 42613). The rep-type cannot be a LONG VARCHAR, LONG VARGRAPHIC, BLOB, CLOB, DBCLOB, DATALINK, or structured type, and must have a length less than or equal to 255 bytes (SQLSTATE 42613).

If this clause is not specified for the root type of a structured type hierarchy, then REF USING VARCHAR(16) FOR BIT DATA is assumed.

CAST (SOURCE AS REF) WITH funcname1
Defines the name of the system-generated function that casts a value with the data type rep-type to the reference type of this structured type. A schema name must not be specified as part of funcname1 (SQLSTATE 42601). The cast function is created in the same schema as the structured type. If the clause is not specified, the default value for funcname1 is type-name (the name of the structured type). A function signature matching funcname1(rep-type) must not already exist in the same schema (SQLSTATE 42710).

CAST (REF AS SOURCE) WITH funcname2
Defines the name of the system-generated function that casts a reference type value for this structured type to the data type rep-type. A schema name must not be specified as part of funcname2 (SQLSTATE 42601). The cast function is created in the same schema as the structured type. If the clause is not specified, the default value for funcname2 is rep-type (the name of the representation type).

method-specification
Defines the methods for this type. A method cannot actually be used until it is given a body with a CREATE METHOD statement (SQLSTATE 42884).

method-name
Names the method being defined. It must be an unqualified SQL identifier (SQLSTATE 42601). The method name is implicitly qualified with the schema used for CREATE TYPE.

A number of names used as keywords in predicates are reserved for system use, and cannot be used as a method-name (SQLSTATE 42939). The names are SOME, ANY, ALL, NOT, AND, OR, BETWEEN, NULL, LIKE, EXISTS, IN, UNIQUE, OVERLAPS, SIMILAR, MATCH and the comparison operators as described in Basic Predicate.

In general, the same name can be used for more than one method if there is some difference in their signatures.

parameter-name
Identifies the parameter name. It cannot be SELF, which is the name for the implicit subject parameter of a method (SQLSTATE 42734). If the method is an SQL method, all its parameters must have names (SQLSTATE 42629).

data-type2
Specifies the data type of each parameter. One entry in the list must be specified for each parameter that the method will expect to receive. No more than 90 parameters are allowed, including the implicit SELF parameter. If this limit is exceeded, an error is raised (SQLSTATE 54023).

SQL data type specifications and abbreviations which may be specified as a column-type in a CREATE TABLE statement and have a correspondence in the language that is being used to write the method may be specified. Refer to the language-specific sections of the Application Development Guide for details on the mapping between SQL data types and host language data types with respect to user-defined functions and methods.
Note:If the SQL data type in question is a structured type, there is no default mapping to a host language data type. A user-defined transform function must be used to create a mapping between the structured type and the host language data type.

DECIMAL (and NUMERIC) are invalid with LANGUAGE C and OLE (SQLSTATE 42815). For alternatives to using DECIMAL, refer to the Application Development Guide.

REF may be specified, but it does not have a defined scope. Inside the body of the method, a reference-type can be used in a path-expression only by first casting it to have a scope. Similarly, a reference returned by a method can be used in a path-expression only by first casting it to have a scope.

AS LOCATOR
For LOB types or distinct types which are based on a LOB type, the AS LOCATOR clause can be added. This indicates that a LOB locator is to be passed to the method instead of the actual value. This saves greatly in the number of bytes passed to the method, and may save as well in performance, particularly in the case where only a few bytes of the value are actually of interest to the method. Use of LOB locators is described in the Application Development Guide.

An error is raised (SQLSTATE 42601) if AS LOCATOR is specified for a type other than a LOB or a distinct type based on a LOB.

If the method is FENCED, or if LANGUAGE is SQL, the AS LOCATOR clause cannot be specified (SQLSTATE 42613).

RETURNS
This mandatory clause identifies the method's result.

data-type3
Specifies the data type of the method's result. In this case, exactly the same considerations apply as for the parameters of methods described above under data-type2.

AS LOCATOR
For LOB types or distinct types which are based on LOB types, the AS LOCATOR clause can be added. This indicates that a LOB locator is to be passed from the method instead of the actual value.

An error is raised (SQLSTATE 42601) if AS LOCATOR is specified for a type other than a LOB or a distinct type based on a LOB.

If the method is FENCED, or if LANGUAGE is SQL, the AS LOCATOR clause cannot be specified (SQLSTATE 42613).

data-type4 CAST FROM data-type5
Specifies the data type of the method's result.

This clause is used to return a different data type to the invoking statement from the data type returned by the method code. The data-type5 must be castable to the data-type4 parameter. If it is not castable, an error is raised (SQLSTATE 42880).

Since the length, precision or scale for data-type4 can be inferred from data-type5, it not necessary (but still permitted) to specify the length, precision, or scale for parameterized types specified for data-type4. Instead, empty parentheses may be used (VARCHAR(), for example). FLOAT() cannot be used (SQLSTATE 42601), since the parameter value indicates different data types (REAL or DOUBLE).

A distinct type is not valid as the type specified in data-type5 (SQLSTATE 42815).

The cast operation is also subject to runtime checks that might result in conversion errors being raised.

AS LOCATOR
For LOB types or distinct types which are based on LOB types, the AS LOCATOR clause can be added. This indicates that a LOB locator is to be passed from the method instead of the actual value.

An error is raised (SQLSTATE 42601) if AS LOCATOR is specified for a type other than a LOB or a distinct type based on a LOB.

If the method is FENCED, or if LANGUAGE is SQL, the AS LOCATOR clause cannot be specified (SQLSTATE 42613).

SPECIFIC specific-name
Provides a unique name for the instance of the method that is being defined. This specific name can be used when creating the method body or dropping the method. It can never be used to invoke the method. The unqualified form of specific-name is an SQL identifier (with a maximum length of 18). The qualified form is a schema-name followed by a period and an SQL identifier. The name, including the implicit or explicit qualifier, must not identify another specific method name that exists at the application server; otherwise an error is raised (SQLSTATE 42710).

The specific-name may be the same as an existing method-name.

If no qualifier is specified, the qualifier that was used for type-name is used. If a qualifier is specified, it must be the same as the explicit or implicit qualifier of type-name or an error is raised (SQLSTATE 42882).

If specific-name is not specified, a unique name is generated by the database manager. The unique name is SQL followed by a character timestamp, SQLyymmddhhmmssxxx.

SELF AS RESULT
Identifies this method as a type-preserving method, which means the following:

SQL-routine-characteristics
Specifies the characteristics of the method body that will be defined for this type using CREATE METHOD.

LANGUAGE SQL
This clause is used to indicate that the method is written in SQL with a single RETURN statement. The method body is specified using the CREATE METHOD statement.

NOT DETERMINISTIC or DETERMINISTIC
This optional clause specifies whether the method always returns the same results for given argument values (DETERMINISTIC) or whether the method depends on some state values that affect the results (NOT DETERMINISTIC). That is, a DETERMINISTIC method must always return the same result from successive invocations with identical inputs. Optimizations taking advantage of the fact that identical inputs always produce the same results are prevented by specifying NOT DETERMINISTIC. NOT DETERMINISTIC must be explicitly or implicitly specified if the body of the method accesses a special register, or calls another non-deterministic routine (SQLSTATE 428C2).

NO EXTERNAL ACTION or EXTERNAL ACTION
This optional clause specifies whether or not the method takes some action that changes the state of an object not managed by the database manager. Optimizations that assume methods have no external impacts are prevented by specifying EXTERNAL ACTION. For example: sending a message, ringing a bell, or writing a record to a file.

READS SQL DATA or CONTAINS SQL
Indicates what type of SQL statements can be executed. Because the SQL statement supported is the RETURN statement, the distinction has to do with whether or not the expression is a subquery.

READS SQL DATA
Indicates that SQL statements that do not modify SQL data can be executed by the method (SQLSTATE 42985). Nicknames cannot be referenced in the SQL statement (SQLSTATE 42997).

CONTAINS SQL
Indicates that SQL statements that neither read nor modify SQL data can be executed by the method (SQLSTATE 42985).

CALLED ON NULL INPUT
This optional clause indicates that regardless of whether any arguments are null, the user-defined method is called. It can return a null value or a normal (non-null) value. However, responsibility for testing for null argument values lies with the method.

The value NULL CALL may be used as a synonym for CALLED ON NULL INPUT for family compatibility.

external-routine-characteristics

LANGUAGE
This mandatory clause is used to specify the language interface convention to which the user-defined method body is written.

C
This means the database manager will call the user-defined method as if it were a C function. The user-defined method must conform to the C language calling and linkage convention as defined by the standard ANSI C prototype.

JAVA
This means the database manager will call the user-defined method as a method in a Java class.

OLE
This means the database manager will call the user-defined method as if it were a method exposed by an OLE automation object. The method must conform with the OLE automation data types and invocation mechanism as described in the OLE Automation Programmer's Reference.

LANGUAGE OLE is only supported for user-defined methods stored in Windows 32-bit operating systems.

PARAMETER STYLE
This clause is used to specify the conventions used for passing parameters to and returning the value from methods.

DB2SQL
Used to specify the conventions for passing parameters to and returning the value from external methods that conform to C language calling and linkage conventions or methods exposed by OLE automation objects. This must be specified when either LANGUAGE C or LANGUAGE OLE is used.

DB2GENERAL
Used to specify the conventions for passing parameters to and returning the value from external methods that are defined as a method in a Java class. This can only be specified when LANGUAGE JAVA is used.

The value DB2GENRL may be used as a synonym for DB2GENERAL.

Refer to the Application Development Guide for details on passing parameters.

DETERMINISTIC or NOT DETERMINISTIC
This optional clause specifies whether the method always returns the same results for given argument values (DETERMINISTIC) or whether the method depends on some state values that affect the results (NOT DETERMINISTIC). That is, a DETERMINISTIC method must always return the same result from successive invocations with identical inputs. Optimizations taking advantage of the fact that identical inputs always produce the same results are prevented by specifying NOT DETERMINISTIC.

An example of a NOT DETERMINISTIC method would be a method that randomly returns a serial number of an employee in a department. An example of a DETERMINISTIC method would be a method that calculates the area of a polygon.

FENCED or NOT FENCED
This clause specifies whether the method is considered "safe" to run in the database manager operating environment's process or address space (NOT FENCED), or not (FENCED).

If a method is registered as FENCED, the database manager insulates its internal resources (data buffers, for example) from access by the method. Most methods will have the option of running as FENCED or NOT FENCED. In general, a method running as FENCED will not perform as well as a similar one running as NOT FENCED.
Note:Use of NOT FENCED for methods not adequately checked out can compromise the integrity of DB2. DB2 takes some precautions against many of the common types of inadvertent failures that might occur, but cannot guarantee complete integrity when NOT FENCED user defined methods are used.

While the use of FENCED does offer a greater degree of protection for database integrity than NOT FENCED, a FENCED method that has not been adequately coded, reviewed and tested can also cause an inadvertent failure of DB2.

Most methods should be able to run either as FENCED or NOT FENCED. Only FENCED can be specified for a method with LANGUAGE OLE (SQLSTATE 42613).

If the method is FENCED, the AS LOCATOR clause cannot be specified (SQLSTATE 42613).

To change from FENCED to NOT FENCED, the method must be re-registered, by first dropping it and then recreating it.

Either SYSADM authority, DBADM authority or a special authority (CREATE_NOT_FENCED) is required to register a method as NOT FENCED.

RETURNS NULL ON NULL INPUT or CALLED ON NULL INPUT
This optional clause may be used to avoid a call to the external method if any of the non-subject arguments is null.

If RETURNS NULL ON NULL INPUT is specified, and if at execution time any one of the method's arguments is null, the method is not called and the result is the null value.

If CALLED ON NULL INPUT is specified, then regardless of the number of null arguments, the method is called. It can return a null value or a normal (non-null) value. However, responsibility for testing for null argument values lies with the method.

The value NULL CALL may be used as a synonym for CALLED ON NULL INPUT for backwards and family compatibility. Similarly, NOT NULL CALL may be used as a synonym for RETURNS NULL ON NULL INPUT.

There are two cases in which this specification is ignored:

  • If the subject argument is null, in which case the method is not executed and the result is null
  • If the method is defined to have no parameters, in which case this null argument condition cannot occur.

NO SQL
This mandatory clauses indicates that the method cannot issue any SQL statements. If it does, an error is raised at run time (SQLSTATE 38502).

EXTERNAL ACTION or NO EXTERNAL ACTION
This optional clause specifies whether or not the method takes some action that changes the state of an object not managed by the database manager. Optimizations that assume methods have no external impacts are prevented by specifying EXTERNAL ACTION.

NO SCRATCHPAD or SCRATCHPAD length
This optional clause may be used to specify whether a scratchpad is to be provided for an external method. It is strongly recommended that methods be re-entrant, so a scratchpad provides a means for the method to "save state" from one call to the next.

If SCRATCHPAD is specified, then at the first invocation of the user-defined method, memory is allocated for a scratchpad to be used by the external method. This scratchpad has the following characteristics:

  • length, if specified, sets the size in bytes of the scratchpad and must be between 1 and 32 767 (SQLSTATE 42820). The default value is 100.
  • It is initialized to all X'00''s.
  • Its scope is the SQL statement. There is one scratchpad per reference to the external method in the SQL statement.

So, if method X in the following statement is defined with the SCRATCHPAD keyword, three scratchpads would be assigned.

     SELECT A, X..(A) FROM TABLEB
        WHERE X..(A) > 103 OR X..(A) < 19

If ALLOW PARALLEL is specified or defaulted to, then the scope is different from the above. If the method is executed in multiple partitions, a scratchpad would be assigned in each partition where the method is processed, for each reference to the method in the SQL statement. Similarly, if the query is executed with intra-partition parallelism enabled, more than three scratchpads may be assigned.

The scratchpad is persistent. Its content is preserved from one external method call to the next. Any changes made to the scratchpad by the external method on one call will be present on the next call. The database manager initializes scratchpads at the beginning of execution of each SQL statement. The database manager may reset scratchpads at the beginning of execution of each subquery. The system issues a final call before resetting a scratchpad if the FINAL CALL option is specified.

The scratchpad can be used as a central point for system resources (memory, for example) which the external method might acquire. The method could acquire the memory on the first call, keep its address in the scratchpad, and refer to it in subsequent calls.

In such a case where system resource is acquired, the FINAL CALL keyword should also be specified; this causes a special call to be made at end-of-statement to allow the external method to free any system resources acquired.

If SCRATCHPAD is specified, then on each invocation of the user-defined method, an additional argument is passed to the external method which addresses the scratchpad.

If NO SCRATCHPAD is specified, then no scratchpad is allocated or passed to the external method.

NO FINAL CALL or FINAL CALL
This optional clause specifies whether a final call is to be made to an external method. The purpose of such a final call is to enable the external method to free any system resources it has acquired. It can be useful in conjunction with the SCRATCHPAD keyword in situations where the external method acquires system resources such as memory and anchors them in the scratchpad.

If FINAL CALL is specified, then at execution time, an additional argument is passed to the external method which specifies the type of call. The types of calls are:

  • Normal call: SQL arguments are passed and a result is expected to be returned.
  • First call: the first call to the external method for this specific reference to the method in this specific SQL statement. The first call is a normal call.
  • Final call: a final call to the external method to enable the method to free up resources. The final call is not a normal call. This final call occurs at the following times:
    • End-of-statement: this case occurs when the cursor is closed for cursor-oriented statements, or when the statement is through executing otherwise.
    • End-of-transaction: This case occurs when the normal end-of-statement does not occur. For example, the logic of an application may for some reason bypass the close of the cursor.

    If a commit operation occurs while a cursor defined as WITH HOLD is open, a final call is made at the subsequent close of the cursor or at the end of the application.

If NO FINAL CALL is specified, then no "call type" argument is passed to the external method, and no final call is made.

ALLOW PARALLEL or DISALLOW PARALLEL
This optional clause specifies whether, for a single reference to the method, the invocation of the method can be parallelized. In general, the invocations of most scalar methods should be parallelizable, but there may be methods (such as those depending on a single copy of a scratchpad) that cannot. If either ALLOW PARALLEL or DISALLOW PARALLEL are specified for a method, then DB2 will accept this specification.

The following questions should be considered in determining which keyword is appropriate for the method:.

  • Are all the method invocations completely independent of each other? If YES, then specify ALLOW PARALLEL.
  • Does each method invocation update the scratchpad, providing value(s) that are of interest to the next invocation (the incrementing of a counter, for example)? If YES, then specify DISALLOW PARALLEL or accept the default.
  • Is there some external action performed by the method which should happen only on one partition? If YES, then specify DISALLOW PARALLEL or accept the default.
  • Is the scratchpad used, but only so that some expensive initialization processing can be performed a minimal number of times? If YES, then specify ALLOW PARALLEL.

In any case, the body of every external method should be in a directory that is available on every partition of the database.

The syntax diagram indicates that the default value is ALLOW PARALLEL. However, the default is DISALLOW PARALLEL if one or more of the following options is specified in the statement:

  • NOT DETERMINISTIC
  • EXTERNAL ACTION
  • SCRATCHPAD
  • FINAL CALL

NO DBINFO or DBINFO
This optional clause specifies whether certain specific information known by DB2 will be passed to the method as an additional invocation-time argument (DBINFO), or not (NO DBINFO). NO DBINFO is the default. DBINFO is not supported for LANGUAGE OLE (SQLSTATE 42613).

If DBINFO is specified, then a structure is passed to the method which contains the following information:

  • Data base name - the name of the currently connected database.
  • Application ID - unique application ID which is established for each connection to the database.
  • Application Authorization ID - the application runtime authorization ID, regardless of the nested methods in between this method and the application.
  • Code page - identifies the database code page.
  • Schema name - under the exact same conditions as for Table name, contains the name of the schema; otherwise blank.
  • Table name - if and only if the method reference is either the right-hand side of a SET clause in an UPDATE statement, or an item in the VALUES list of an INSERT statement, contains the unqualified name of the table being updated or inserted; otherwise blank.
  • Column name - under the exact same conditions as for Table name, contains the name of the column being updated or inserted; otherwise blank.
  • Database version/release - identifies the version, release and modification level of the database server invoking the method.
  • Platform - contains the server's platform type.
  • Table method result column numbers - not applicable to methods.

Refer to Application Development Guide for detailed information on the structure and how it is passed to the method.

Notes

Examples

Example 1:  Create a type for department.

     CREATE TYPE DEPT AS
        (DEPT NAME     VARCHAR(20),
           MAX_EMPS INT)
           REF USING INT
        MODE DB2SQL

Example 2:  Create a type hierarchy consisting of a type for employees and a subtype for managers.

     CREATE TYPE EMP AS
       (NAME      VARCHAR(32),
        SERIALNUM INT,
        DEPT      REF(DEPT),
        SALARY    DECIMAL(10,2))
        MODE DB2SQL
 
     CREATE TYPE MGR UNDER EMP AS
       (BONUS     DECIMAL(10,2))
        MODE DB2SQL

Example 3:  Create a type hierarchy for addresses. Addresses are intended to be used as types of columns. The inline length is not specified, so DB2 will calculate a default length. Encapsulate within the address type definition an external method that calculates how close this address is to a given input address. Create the method body using the CREATE METHOD statement.

     CREATE TYPE address_t AS
        (STREET     VARCHAR(30),
         NUMBER     CHAR(15),
         CITY       VARCHAR(30),
         STATE      VARCHAR(10))
         NOT FINAL
         MODE DB2SQL
            METHOD SAMEZIP (addr address_t)
            RETURNS INTEGER
            LANGUAGE SQL
            DETERMINISTIC
            CONTAINS SQL
            NO EXTERNAL ACTION
 
            METHOD DISTANCE (address_t)
            RETURNS FLOAT
            LANGUAGE C
            DETERMINISTIC
            PARAMETER STYLE DB2SQL
            NO SQL
            NO EXTERNAL ACTION
 
     CREATE TYPE germany_addr_t UNDER address_t AS
        (FAMILY_NAME VARCHAR(30))
         NOT FINAL
         MODE DB2SQL
 
     CREATE TYPE us_addr_t UNDER address_t AS
         (ZIP VARCHAR(10))
          NOT FINAL
          MODE DB2SQL

Example 4:  Create a type that has nested structured type attributes.

     CREATE TYPE PROJECT AS
           (PROJ_NAME  VARCHAR(20),
            PROJ_ID    INTEGER,
            PROJ_MGR   MGR,
            PROJ_LEAD  EMP,
            LOCATION   ADDR_T,
            AVAIL_DATE DATE)
            MODE DB2SQL


Footnotes:

85
All references in a type hierarchy have the same reference representation type. This enables REF(S) and REF(T) to be compared provided that S and T have a common supertype. Since uniqueness of the OID column is enforced only within a table hierarchy, it is possible that a value of REF(T) in one table hierarchy may be "equal" to a value of REF(T) in another table hierarchy, even though they reference different rows.


[ Top of Page | Previous Page | Next Page ]