C.Mayers
C.Mayers

Reputation: 91

Oracle SQL DB: If equal to Monday then perform a certain statement

I'm using a SQL statement in Power BI on a Oracle based system to pull some data when the day of the week equals Monday. Ideally, I'm trying to make it so it works in any location. I'm trying to convert "C_endtime" to a day of the week and compare it to the sysdate. Basically if its Monday then I want all the data from that table back to Friday, every other day would just be the previous day's data.

In other words what I'm ultimately shooting for is:

...
where
if 
   sysdate = 1 (Monday) 
then 
   pull data back 3 days (sysdate -3) 
else 
   one day (sysdate -1) 

Here is my attempt:

SELECT 
   Example Fields                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
FROM 
   Example Table
WHERE

TO_CHAR(c_endtime, 'D', 'NLS_DATE_LANGUAGE=ENGLISH')  >
   CASE TO_CHAR(sysdate, 'D', 'NLS_DATE_LANGUAGE=ENGLISH') 
      WHEN '1' then sysdate - 3
   ELSE
      sysdate - 1
   END 

AND 
   c_workcentrename = ####

I get the error: "ORA-01840: input value not long enough for date format."

Upvotes: 1

Views: 905

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269463

Assuming that on Monday you want everything since the beginning of Friday and on other days since the beginning of the previous day, then you can use logic like this:

select . . .
from . . .
where ( (trunc(sysdate) = trunc(sysdate, 'IW') and c_endtime >= trunc(sysdate - 3)) or
        (trunc(sysdate <> trunc(sysdate, 'IW') and c_endtime > trunc(sysdate - 1))
      ) and
      c_workcentrename = ###;

ISO weeks start on Monday and that is not changing anytime soon or in any environment.

You can simplify the above to:

where ( (trunc(sysdate) = trunc(sysdate, 'IW') and c_endtime >= trunc(sysdate - 3)) or
        (c_endtime >= trunc(sysdate - 1))
      ) and
      c_workcentrename = ###;

Upvotes: 1

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59436

The result of TO_CHAR(c_endtime, 'D') depends on the current user session NLS-Setting, i.e. result is not predictable.

Better use condition like this:

IF TO_CHAR(c_endtime, 'fmDay', 'NLS_DATE_LANGUAGE = American') = 'Monday' THEN

or

TRUNC(c_endtime) = TRUNC(c_endtime, 'IW') THEN

Upvotes: 2

Related Questions