Pergunta

I have a function in Oracle that checks if the first date contains the second one. There is no problem with it, because [a, b] contains [x, y] if x => a and y <= b and x <= y. Works fine for defined start/end date 1 and start/end date 2. But now I want to modify it. If any of given 'starting' dates is NULL it should be treated as +-infinite.

It's a code:

  FUNCTION CONTAINS(p_START_DATE_1 DATE, p_END_DATE_1 DATE,
   p_START_DATE_2 DATE, p_END_DATE_2 DATE) RETURN VARCHAR2 AS

   lv_RESULT VARCHAR2(1);
  BEGIN 
       lv_RESULT := 'N';      

       IF (/* milions of conditions here */) THEN
         lv_RESULT := 'Y';
       END IF;

       RETURN lv_RESULT;
  END CONTAINS;

For instance: Suppose that p_START_DATE_1 is NULL. In this case that code:

SELECT MY_PACKAGE_SQL.CONTAINS(
       NULL,
       TO_DATE('01/12/2014', 'DD/MM/YYYY'),
       TO_DATE('01/02/2012', 'DD/MM/YYYY'),
       TO_DATE('01/05/2012', 'DD/MM/YYYY'))
FROM DUAL;

... should return Y, because first date range is (-infinite, 01/12/2014] and it contains [01/02/2012, 01/05/2012].

Now my problem... I know I can use additional "IFs" to check NULLs. But I wonder if it's any other solution to make it faster in Oracle's PL\SQL language? It's like do it in smarter way challenge in my team :)

Foi útil?

Solução

If only dates can't be null you can put it like that:

  IF ((p_END_DATE_1 >= p_START_DATE_2) AND
      (p_START_DATE_1 <= p_END_DATE_2)) THEN 
    lv_RESULT := 'Y';
  END IF;

when having nulls you can declare that, say

  -Infinity == 1 Jan 1
  +Infinity == 31 Dec 3999 

So with a help of Coalesce or Nvl function you can implement

  IF (coalesce(p_END_DATE_1, TO_DATE('31.12.3999', 'dd.mm.yyyy')) >=
      coalesce(p_END_DATE_2, TO_DATE('31.12.3999', 'dd.mm.yyyy')) AND
      coalesce(p_START_DATE_1, TO_DATE('1.1.1', 'dd.mm.yyyy')) <= 
      coalesce(p_START_DATE_2, TO_DATE('1.1.1', 'dd.mm.yyyy'))) THEN 
    lv_RESULT := 'Y';
  END IF;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top