select max of date with query - java

I want to select max of date in hibernate but I get this error:
java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes:
expected TIMESTAMP got NUMBER
The query is :
select coalesce(max (rc.dateTransactionReceipt),0 ) from MAMReceiptTransactions rc where rc.mamItems.id =m.id ) as lastDateOfCharge
and the database is oracle.
Type of this field in database is TIMESTAMP(6)

Trying to get 0 when timestamp doesn't make sense apart from being syntactically incorrect (The datatypes of the coalesce parameters must be compatible). Null itself sounds reasonable.
select max(rc.dateTransaction) from your_table rc
If you want to have a default timestamp returned, you can use that in the coalesce instead. Perhaps you want current timestamp returned in case the above returns null.
select coalesce(max(rc.dateTransaction), systimestamp) from your_table rc;

Related

Unexpected token "(" - Java -- SQL Server

I am using the Niagara 4 Framework (Java) where I want to send queries to my SQL Server database.
Here is my query : (it does work in SQL Server)
SELECT * FROM [RESTART]
WHERE TIMESTAMP > CURRENT_TIMESTAMP and TIMESTAMP <DATEADD(minute, 10,
CURRENT_TIMESTAMP )
And I get the following error :
Syntax error near:"DATEADD(" Unexpected token "(" at line 0, column 11.
Any idea why do I get this ?
your code with the table name and field name switch to a table I have executes with out error in SSMS,
SELECT * FROM [OutgoingAudit]
WHERE CreateTS > CURRENT_TIMESTAMP and CreateTS < DATEADD(minute, 20, CURRENT_TIMESTAMP )
that being said the first part of your where
WHERE TIMESTAMP > CURRENT_TIMESTAMP
unless TIMESTAMP is a future it will never happen, but that may be what you are looking for
TIMESTAMP and CURRENT_TIMESTAMP are both reserved words in SQL Server.
Try changing TIMSTAMP to MY_TIMESTAMP
Also, contrary to what the name suggests, TIMESTAMP is not actually a time, but CURRENT_TIMESTAMP is...
The TIMESTAMP data type is just an incrementing number and does not preserve a date or a time.
and
CURRENT_TIMESTAMP returns the current database system timestamp as a datetime value without the database time zone offset.
So comparing a TIMESTAMP (not a time) to CURRENT_TIMESTAMP (yes a time) is likely causing problems.

Error inserting null or empty value in DATE column mapped to LocalDate type in java

I am using MS SQL as my DB and I have a DATE column called 'START_DATE' in one of my tables. This is a non mandatory column.
In my java layer I am have mapped this to the LocalDate . When I dont have any value set for START_DATE, then I set it to null or leave it empty.
In both cases I get the error that
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Implicit conversion from data type varbinary to date is not allowed. Use the CONVERT function to run this query.
How do I fix this, please advise?
Are you using 2012 version or newer? The problem is in the way SQL 2012 interprets null values for a datetime time. Insert query from Java should have an explicit convert function to forcefully insert it as datetime to avoid this unexpected error.
Something like:
convert(DATETIME,START_DATE,21)
More info
I had the same issue with SQL Server. I fixed it by changing the insert value from just myValue to
CONVERT(DATE, myValue)

How to set java.sql.Timestamp in prepared statement when used for TIMESTAMPDIFF calculation?

I am currently facing the following issue:
I want to get the time difference in seconds between the current time and the given timestamp in a prepared statement.
public List<Foo> getFoos(String id, Timestamp ts) {
return jdbcTemplate.query(
"SELECT TIMESTAMPDIFF(2, (CURRENT TIMESTAMP - ?)) AS NEW_TIMESTAMP FROM SCHEMA.TABLE WHERE ID = ?",
new Object[]{ts, id},
(rs, rowNum) -> mapFooFromResultSet());
}
This query will fail with
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-402, SQLSTATE=42819, SQLERRMC=-, DRIVER=
-402 AN ARITHMETIC FUNCTION OR OPERATOR function-operator IS APPLIED TO CHARACTER OR DATETIME DATA
I am using a DB2 database and cannot switch to any other db driver.
So my question would be how do I achieve the time difference in a sql statement between the current time and a given java.sql.Timestamp value?
Thank you in advance for your help.
It seems that the function TIMESTAMPDIFF does not accept a Timestamp, but expects a String value like specified in the string-expression paragraph of the docs. In the examples they make use of the CAST, CHAR and TIMESTAMP functions, so the following might solve the problem.
Instead of a Timestamp object, a corresponding String value needs to be specified in the format YYYY-MM-DD-hh.mm.ss:
SELECT TIMESTAMPDIFF(2, CHAR(CURRENT TIMESTAMP - TIMESTAMP(?))) AS NEW_TIMESTAMP
FROM SCHEMA.TABLE
WHERE ID = ?
As mentioned by #Idz the TIMESTAMPDIFF expects a string-expression. Look at the last example on the provided website you will see a solution.
For my example it works with the following code:
"SELECT TIMESTAMPDIFF(2, CAST(CURRENT_TIMESTAMP - CAST(? AS TIMESTAMP) AS CHAR(22))) AS NEW_TIMESTAMP FROM SCHEMA.TABLE WHERE ID = ?"

PostgreSQL query works in pgAdmin but not in Java EclipseLink

I have a SQL that counts rows per date truncate (months, days, hours). Think a history graph. Query works fine if executed in pgAdmin but fails in Java using EclipseLink.
pgAdmin query:
SELECT date_trunc( 'hour', delivered_at ),
COUNT(date_trunc( 'hour', delivered_at )) AS num
FROM messages
WHERE channel_type='EMAIL'
AND created_at>='2016-02-28 16:01:08.882'
AND created_at<='2016-02-29 16:01:08.882'
GROUP BY date_trunc( 'hour', delivered_at );
JPQL Named query
SELECT FUNCTION('date_trunc', 'hour', m.deliveredAt ),
COUNT(FUNCTION('date_trunc', 'hour', m.deliveredAt )) AS num
FROM Message m
WHERE m.channelType = :channelType
AND m.createdAt >= :fromDate
AND m.createdAt <= :toDate
GROUP BY FUNCTION('date_trunc', 'hour', m.deliveredAt )
EclipseLink debugging log:
SELECT date_trunc(?, delivered_at), COUNT(date_trunc(?, delivered_at)) FROM messages
WHERE (((channel_type = ?) AND (created_at >= ?)) AND (created_at <= ?)) GROUP BY date_trunc(?, delivered_at)
bind => [hour, hour, EMAIL, 2015-12-27 00:00:00.0, 2015-12-27 00:00:00.0, hour]
Error:
ERROR: column "messages.delivered_at" must appear in the GROUP BY
clause or be used in an aggregate function Position: 23
PostgreSQL log:
2016-03-01 13:22:08 CET ERROR: column "messages.delivered_at" must
appear in the GROUP BY clause or be used in an aggregate function at
character 23 2016-03-01 13:22:08 CET STATEMENT: SELECT date_trunc($1,
delivered_at), COUNT(delivered_at) FROM messages WHERE (((channel_type
= $2) AND (created_at >= $3)) AND (created_at <= $4)) GROUP BY date_trunc($5, delivered_at) 2016-03-01 13:22:08 CET LOG: execute
S_2: SELECT 1
If I replace the binded variables from EclipseLink logged query and execute it in pgAdmin the query works. What is going on here?
Edit: Just to clarify, it also works using em.createNativeQuery.
PostgreSQL can have trouble with resolving parameter binding, which in this case manifests as native SQL with parameters inline work, while JPA generated SQL which defaults to bound parameters fails.
One solution is to turn off parameter binding by passing "eclipselink.jdbc.bind-parameters" with a value of "false" as either a query hint for the specific query, or as a persistence unit property to turn off parameter binding by default for all queries.
On postgresql, you can use the following syntax
GROUP BY 1
That means you will group you agregate using the first selected attribute in the SELECT clause. That might be helpful there

The column name is not valid - error

I am getting this error while I am fetching value from resultset.
Error : com.microsoft.sqlserver.jdbc.SQLServerException: The column name company.short_name is not valid
CASE 1 :
select company.short_Name,location_name from company,location;
this query is executing fine on SQL Server but in my java code when I trying to retrieve value like resultset.getString("company.short_name"); that time this give the above error.
CASE 2 :
select company.short_Name short_name,location_name from company,location;
and retrieve value like resultset.getString("short_name"); than it work fine with both database MySQL and MSSQL.
I am migrating my database from MySQL to MSSQL.above case 1 is work fine in MySQL, but why it is not work in MSSQL?
resultset.getString("company.short_name"); is wrong here. No need to specifying fully qualified name while trying to fetch the data in your application. Just specify the column name like resultset.getString("short_name");.
Cause even though you say select company.short_Name ... query out the column name as short_Name since that's what defined in table schema.
In case both tables has same column which may result in ambiguity, give a alias name to the columns like
select company.short_Name as company_shortname,
location.short_Name as location_shortname,
location.location_name from company,location;
add the following to your application.properties file
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
When you do
select company.short_Name,location_name from company,location;
This query outs the column name short_Name and resultSet would also have short_Name
since the company.short_name doesnt exist you get an error.
the function resultset.getString(String columnLabel)
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
Parameters:
columnLabel the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is null
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set
in the function resultset.getString(String columnLabel), the arg is a column name for executing sql, the statement select company.short_Name,location_name from company,location; will get a result set, which has table headers short_Name,location_name

Categories