Home > other >  Conditional where clause in Oracle SQL query is not working
Conditional where clause in Oracle SQL query is not working

Time:11-06

I am trying to do a select on Oracle DB with this condition but it is not working.

LocalDateTime endDate = null;

Table POST

ID NUMBER
DATE_END TIMESTAMP(6)
select p.id from post p where (:endDate is null or p.date_end < :endDate);

but when endDate is null I got the error

ORA-00932 inconsistent datatypes expected TIMESTAMP got NUMBER.

Please help

CodePudding user response:

try

select p.id
  from post p
 where (to_date(:endDate, 'dd/mm/yyyy') is null
    or p.date_end < to_date(:endDate, 'dd/mm/yyyy'));

CodePudding user response:

Sample Setup

create table test (
DATE_END TIMESTAMP);

insert into test values (timestamp  '2009-12-26 22:22:22.123456');
insert into test values (timestamp  '2009-12-26 22:22:22.123458');

This query simulates your exception

select * from test where DATE_END > 1;
ORA-00932: inconsistent datatypes: expected TIMESTAMP got NUMBER

So you most probably use some incorrect set method for the bind variable.

Anyway setTimestamp works with JDBC Driver 12.1.0.2.0 on 18 XE

def stmt = con.prepareStatement("select DATE_END from test where ? is null or DATE_END > ?")
stmt.setTimestamp(1,null)
stmt.setTimestamp(2,null)

def rs = stmt.executeQuery()
while(rs.next())
 {
   println "ts= ${rs.getTimestamp(1)}"
 }

returns both rows

ts= 2009-12-26 22:22:22.123456 
ts= 2009-12-26 22:22:22.123458

While is you pass a real timestamp you get a limited result

def ts = java.sql.Timestamp.valueOf('2009-12-26 22:22:22.123457')

def stmt = con.prepareStatement("select DATE_END from test where ? is null or DATE_END > ?")
stmt.setTimestamp(1,ts)
stmt.setTimestamp(2,ts)
...

ts= 2009-12-26 22:22:22.123458
  • Related