简体   繁体   中英

Conditional where clause in Oracle SQL query is not working

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

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'));

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

解决方案是转换字符串中的日期,并在选择中执行此操作和 (:endDate is null or pl.date_end <= TO_DATE(:endDate , 'yyyy-MM-dd HH:MI:SS'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM