views:

529

answers:

1

Why isn't my PL/SQL duration function working correctly? In the query below, I manually calculate the 'hh:mm' the same way as in the function below. However, I get different results.

Calling Query:

WITH durdays AS (SELECT SYSDATE - (SYSDATE - (95 / 1440)) AS durdays FROM DUAL)
SELECT TRUNC (24 * durdays) AS durhrs,
       MOD (TRUNC (durdays * 1440), 60) AS durmin,
       steven.duration (SYSDATE - (95 / 1400), SYSDATE) duration
  FROM durdays

Output:

durhrs:   1
durmin:   35
duration: '1:38'

Function code:

CREATE OR REPLACE FUNCTION steven.duration (d1 IN DATE, d2 IN DATE)
   RETURN VARCHAR2 IS
   tmpvar   VARCHAR2 (30);
   durdays   NUMBER (20,10); -- Days between two DATEs
   durhrs   BINARY_INTEGER; -- Completed hours
   durmin   BINARY_INTEGER; -- Completed minutes
BEGIN
   durdays   := d2-d1; 
   durhrs   := TRUNC(24 * durdays);   
   durmin   := MOD (TRUNC(durdays * 1440), 60);
   tmpvar   := durhrs || ':' || durmin;
   RETURN tmpvar;
END duration;
/
+5  A: 

Hi Steven,

I think you might have a small typo:

WITH durdays AS (SELECT SYSDATE - (SYSDATE - (95 / 1440)) AS durdays FROM DUAL)
                                                   ^^^^
SELECT TRUNC (24 * durdays) AS durhrs,
       MOD (TRUNC (durdays * 1440), 60) AS durmin,
       lims_sys.duration (SYSDATE - (95 / 1400), SYSDATE) duration
                                          ^^^^

Once this is fixed it works OK:

SQL> WITH durdays AS (SELECT SYSDATE - (SYSDATE - (95 / 1440)) AS durdays FROM DUAL)
  2  SELECT TRUNC (24 * durdays) AS durhrs,
  3         MOD (TRUNC (durdays * 1440), 60) AS durmin,
  4         duration (SYSDATE - (95 / 1440), SYSDATE) duration
  5    FROM durdays
  6  ;

    DURHRS     DURMIN DURATION
---------- ---------- ----------------
         1         34 1:34
Vincent Malgrat
Just needed a second set of eyes to look at it. Thanks!
Steven
Glad to help =)
Vincent Malgrat