Quote:
|
Originally Posted by sathyaram_s
Your question is : Can you pass a query as input to a UDF and get the result set of the query as output of table function.
The simple answer is Yes. (Disclaimer: AFAIK … I have not tried defining external table function myself)
|
You can remove the
AFAIK. It is definitively possible. As we explained extensively before (primarily in the DB2 newsgroup), there are a lot of examples shipped with DB2 that show how to implement table functions. You have to declare and open a cursor inside the table function in the OPEN call, and each FETCH call to the UDF translates to a FETCH on the cursor. When DB2 makes the SQLUDF_TF_CLOSE call to the table UDF, you close the cursor. It's simple as that - and exactly the same you would have to do when implementing a ResultSet class in Java if you were to write a JDBC driver.
You (the OP) should simply give it a try and if it does not work, ask specific questions...
Quote:
There are a few more points to remember though:
a) your resultset column names will be as per your UDF definition and NOT as per your input query.
|
That is not much of a problem because you can simply (re)name the columns of every table that occurs in the FROM clause:
Code:
SELECT ... FROM TABLE ( func(...) ) AS func_result_table(a, b, c)
or this for base tables, views, and nicknames:
Code:
SELECT ... FROM t1 AS t(a, b, c)
Quote:
b) The number and datatypes of the resultset columns is fixed at the UDF definition time.
As example for above , If you define your UDF :
Code:
CREATE FUNCTION MYFUNC(QRY VARCHAR(1000))
RETURNS TABLE (TIMERECEIVED DATE,
SUBJECT VARCHAR(15))
Then your call,
Code:
Select * from table (‘myfunc(select date(timestampcol) as d,namecol as n from employee’) as udf
Then your resultset will have the column names TIMERECEIVED and SUBJECT and not D and N.
You call cannot be :
Code:
Select * from table (‘myfunc(select date(timestampcol) as d,namecol as n , salarycol from employee’) as udf
|
Actually, you can provide such a query (with corrected positioning of the single-quotes). As long as the table function makes sure that only two columns are returned to DB2 and the third column is ignored. The only other criteria is that the data types match with whatever was defined at CREATE FUNCTION time, as you already pointed out.