问题
This is my sql string from which I prepare statement:
SELECT (DAYS(?) - DAYS(FROM)) * 86400 + (MIDNIGHT_SECONDS(?) -
MIDNIGHT_SECONDS(FROM)) AS FROM_DIFF,
(DAYS(?) - DAYS(TO)) * 86400 + (MIDNIGHT_SECONDS(?) -
MIDNIGHT_SECONDS(TO)) AS TO_DIFF
FROM CALENDAR.EVENTS WHERE ID = ?
fill values with the following code:
ps.setTimestamp(1, new Timestamp(...));
ps.setTimestamp(2, new Timestamp(...));
ps.setTimestamp(3, new Timestamp(...));
ps.setTimestamp(4, new Timestamp(...));
ps.setInt(5, ...);
And get an exception:
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-245, SQLSTATE=428F5, SQLERRMC=DAYS;1, DRIVER=4.16.53
When I run it directly from SQL browser it run flawlessly:
SELECT
(DAYS('2015-05-05 00:00:00.0') - DAYS(FROM)) * 86400 + (MIDNIGHT_SECONDS('2015-05-05 00:00:00.0') - MIDNIGHT_SECONDS(FROM)) AS FROM_DIFF,
(DAYS('2015-05-05 00:00:00.0') - DAYS(TO)) * 86400 + (MIDNIGHT_SECONDS('2015-05-05 00:00:00.0') - MIDNIGHT_SECONDS(TO)) AS TO_DIFF
FROM CALENDAR.EVENTS WHERE ID = 1055;
Where is a mistake?
Thank you.
P.S. Formula how to calculate time difference is taken from this article: DB2 Basics: Fun with Dates and Times
回答1:
There are several overloaded versions of the DAYS() function, accepting parameters with different data types: DATE, TIMESTAMP, and VARCHAR. When you use an untyped parameter marker (DAYS(?)) the query compiler is unable to determine which version of the function to use in the query.
You can specify the parameter data type explicitly for compilation: DAYS(CAST(? AS TIMESTAMP)). Alternatively, if you are using a recent DB2 for LUW version (9.7 and higher) you can set the DB2 registry variable:
db2set DB2_DEFERRED_PREPARE_SEMANTICS=YES
to tell the compiler that it should defer the PREPARE call until the query execution time, when parameter data types are already known.
来源:https://stackoverflow.com/questions/30213857/db2-when-trying-to-calculate-difference-between-provided-and-stored-timestamp-i