Specifying UDTF arguments and return values

Like a UDSF, a UDTF can also take advantage of size-specific, generic, and variable-size arguments.

When you register a UDTF, you specify the table shape of its return values. You can specify either:
  • A specific table shape.
  • GENERIC TABLE. which indicates that the table shape of the return values is to be based on the input arguments and the UDTF program design. For example:
    CREATE OR REPLACE FUNCTION MYTF(INTEGER, VARCHAR(128))
    RETURNS GENERIC TABLE
    ⋮

When you specify GENERIC TABLE, the Db2® database engine instantiates the UDTF and invokes the calculateShape() method during query preparation time to get the table definition from the UDTF.

virtual void calculateShape(UdxOutputShaper *shaper)
A Db2 instance provides shaper methods that you can use to collect information about the input columns (including constant values) and to provide information about the output shape. The following example uses the calculateShape() method:
  void calculateShape(UdxOutputShaper *shaper) {
    if (shaper->numArgs() != 1)
      throwUdxException("Expecting only one argument");
    int nType = shaper->argType(0);
    if ((UDX_FIXED == nType) || (UDX_VARIABLE == nType)) {
      int len = shaper->stringArgSize(0);
      char ucstr[] = "UPPER_CASE"; // For column names on systems that
      char lcstr[] = "lower_case"; // use lowercase naming 
      char tcstr[] = "Title_Case";
      char ucstrU[] = "UPPER_CASE"; // For column names on systems
      char lcstrU[] = "LOWER_CASE"; // that use uppercase naming
      char tcstrU[] = "TITLE_CASE";
      if (shaper->isSystemCaseUpper()) {
        shaper->addOutputColumn(nType, ucstrU, len);
        shaper->addOutputColumn(nType, lcstrU, len);
        shaper->addOutputColumn(nType, tcstrU, len);
      }
      else {
        shaper->addOutputColumn(nType, ucstr, len);
        shaper->addOutputColumn(nType, lcstr, len);
        shaper->addOutputColumn(nType, tcstr, len);
      }
    }
    else {
      throwUdxException("Only CHAR and VARCHAR types can be used");
    }
  }
In this example, the UDTF takes an input string and returns three columns of data:
  • An uppercase version of the string
  • A lowercase version of the string
  • An initial capital letter version of the string
The shaper verifies that only one string is input at a time, and that the string is of type CHAR or VARCHAR. The function also displays the column headings by using a mixed capitalization on systems where the system casing is lowercase or all uppercase characters on systems where the case is uppercase.