Compare with previous date in oracle

2

Hello,

I need to check which purchases have been made in the last 7 days

select * from carros car  where to_date(to_char(to_date(car.datacompra,'yyyymmdd'),'dd-mm-yyyy')) = trunc(sysdate - 7)

I get the following error:

ORA-01840: valor de entrada não é longo o suficiente para formato de data

Thank you

    
asked by anonymous 25.07.2016 / 15:21

2 answers

2

To_date expects to receive a char, if its field is of type Number, then you need to do the first parse of number for char.

select * from carros car  where to_date(to_char(to_date(to_char(car.datacompra),'yyyymmdd'),'dd-mm-yyyy')) = trunc(sysdate - 7)

Source: TO_DATE Documentation

Issue 1

My first correction proposal was not adequate, I think this query will better suit your needs:

select * from carros car where to_date(LPAD(to_char(car.datacompra), 8,'0'),'yyyymmdd')= trunc(sysdate - 7) 

I removed some transformations, and added the LPAD, to ensure to_date will work, preventing the error from occurring.

LPAD Documentation

    
25.07.2016 / 15:56
0

And if you do it simply:

SELECT *
  FROM carros car
 WHERE TO_DATE(car.datacompra,'YYYY-MM-DD') =
       TRUNC(SYSDATE-7)
    
25.07.2016 / 16:21