Example: Table function returning document IDs

In this example, you have written a table function that returns a row consisting of a single document identifier column for each known document in your text management system that matches a given subject area (the first parameter) and contains the given string (second parameter).

This UDF uses the functions of the text management system to quickly identify the documents:

     CREATE FUNCTION DOCMATCH (VARCHAR(30), VARCHAR(255))
       RETURNS TABLE (DOC_ID CHAR(16))
       EXTERNAL NAME 'DOCFUNCS/UDFMATCH(udfmatch)'
       LANGUAGE C
       PARAMETER STYLE DB2SQL
       NO SQL
       DETERMINISTIC
       NO EXTERNAL ACTION
       NOT FENCED
       SCRATCHPAD
       NO FINAL CALL
       DISALLOW PARALLEL
       CARDINALITY 20

Within the context of a single session it will always return the same table, and therefore it is defined as DETERMINISTIC. The RETURNS clause defines the output from DOCMATCH, including the column name DOC_ID. FINAL CALL does not need to be specified for this table function. The DISALLOW PARALLEL keyword is required since table functions cannot operate in parallel. Although the size of the output from DOCMATCH can be a large table, CARDINALITY 20 is a representative value, and is specified to help the optimizer make good decisions.

Typically, this table function is used in a join with the table containing the document text, as follows:

     SELECT T.AUTHOR, T.DOCTEXT
       FROM DOCS AS T, TABLE(DOCMATCH('MATHEMATICS', 'ZORN''S LEMMA')) AS F
       WHERE T.DOCID = F.DOC_ID

Note the special syntax (TABLE keyword) for specifying a table function in a FROM clause. In this invocation, the DOCMATCH() table function returns a row containing the single column DOC_ID for each MATHEMATICS document referencing ZORN'S LEMMA. These DOC_ID values are joined to the master document table, retrieving the author's name and document text.