I am struggeling with exception handling of User Defined Functions (UDF) in DB2.
The starting postion of my problem is, that I want to SELECT over a table with varchar-timestamps in a specific format and convert them into timestamp-datatype.
The following SQL-Statements shows a positiv szenario. All varchar-timestamps are valid. The SELECT will succeed:
DROP TABLE TMP_TSP;
CREATE TABLE TMP_TSP (TSP_VARCHAR VARCHAR(100) NOT NULL UNIQUE);
INSERT INTO TMP_TSP VALUES ('2017-02-27');
INSERT INTO TMP_TSP VALUES ('2017-02-28');
SELECT TSP_VARCHAR, timestamp_format(TSP_VARCHAR, 'YYYY-MM-DD') TSP FROM tmp_tsp;
So far so good. But if the table contains an invalid varchar-timestamp the SELECT-Statement fails:
DROP TABLE TMP_TSP;
CREATE TABLE TMP_TSP (TSP_VARCHAR VARCHAR(100) NOT NULL UNIQUE);
INSERT INTO TMP_TSP VALUES ('2017-02-27');
INSERT INTO TMP_TSP VALUES ('2017-02-28');
INSERT INTO TMP_TSP VALUES ('2017-02-29'); -- Invalid Date!
select TSP_VARCHAR, timestamp_format(TSP_VARCHAR, 'YYYY-MM-DD') TSP from tmp_tsp;
The execution of the SELECT-Statement is interupted with the following errormessage:
[Error Code: -20448, SQL State: 22007] "2017-02-29" cannot be interpreted using format string "YYYY-MM-DD" for the TIMESTAMP_FORMAT function.. SQLCODE=-20448, SQLSTATE=22007
I am searching for a solution to SELECT those timestamps exception-safe, that means, if a varchar-timestamp is valid, it should be converted into timestamp, and if it is invalid, like '2017-02-29', null should be returned. The SELECT-Statement should have the following result:
2017-02-27 2017-02-27 00:00:00
2017-02-28 2017-02-28 00:00:00
2017-02-29 null
I tried to create an UDF which encapsulates the function timestamp_format and adds some logic for exception handling, e.g. via DECLARE CONTINUE HANDLER. Unfortunately I did not succeed on this way until now.
I am using DB2/LINUXX8664 10.5.7.
May be You can help?! Many thanks in advance!