问题
I need to create function in Informix that calculates number of working days in between two given dates. I have created table "prazkal" with holidays, and two Informix functions:
create function is_holiday(d datetime year to day)
returning boolean;
define hcnt integer;
if weekday(d) = 0 or weekday(d) = 6 then
return 't';
end if;
---code that check if 'd' is marked as holiday in calendar
select count(*) into hcnt from prazkal where datpra = d;
if hcnt > 0 then
return 't';
end if;
return 'f';
end function;
create function work_days(start_d DATE, end_d DATE)
returning integer;
define new_d datetime year to day;
define count_days integer;
define i integer;
let i = 0;
let count_days = end_d - start_d;
let new_d = CAST(end_d AS DATETIME YEAR TO DAY);
while i < count_days
let new_d = new_d - interval(1) day to day;
if not is_holiday(new_d) then
let i = i + 1;
end if;
end while
return i;
end function;
Both of my functions are modified from this post. Result of function work_days is number of days between two dates (end_d, start_d), and not number of working days. Where did I made error?
回答1:
Your loop increments i
until it is the number in count_days
, so the answer will always be count_days
(calculated very slowly). You need a second condition new_d > start_d
too:
while i < count_days and new_d > start_d
let new_d = new_d - interval(1) day to day;
if not is_holiday(new_d) then
let i = i + 1;
end if;
end while
The >
is appropriate since the loop decrements and then checks new_d
, so the last cycle tests start_d
.
来源:https://stackoverflow.com/questions/29748645/how-to-get-number-of-working-days-in-informix-between-two-dates