CREATE OR REPLACE Package Acueducto is
  FUNCTION Consumo(Vant in number, Vact in number) RETURN number;
  FUNCTION MontoServicio(Vcia in char, Vserv in char, consumo in number) RETURN number;
end;
/


CREATE OR REPLACE Package Body Acueducto is

  FUNCTION Consumo(Vant in number, Vact in number) RETURN number IS
  BEGIN
   if nvl(Vant,0)>nvl(Vact,0) then
      return nvl(Vact,0)-nvl(Vant,0)+10000;
   else
      return nvl(Vact,0)-nvl(Vant,0);
   end if; 
  END;

  FUNCTION MontoServicio(Vcia in char, Vserv in char, consumo in number) RETURN number IS
   minimo   acuservicio.consumominimo%type;
   real     acuservicio.consumominimo%type;
   antdes   acutarifa.desde%type;
   antpre   acutarifa.costom3%type;
   cursor tractos is
      select desde, costom3
      from acutarifa
      where cia=Vcia
        and servicio=Vserv
        and desde<consumo
      order by desde desc;
  BEGIN
   select nvl(consumominimo,0) into minimo
   from acuservicio
   where cia=Vcia
     and servicio=Vserv;
   antdes:=consumo;
   real:=0;
   for d in tractos 
   loop
      real:=real+(antdes-d.desde)*d.costom3;
      antdes:=d.desde;
   end loop;
   return nvl(minimo,0)+nvl(real,0);
  END;


END;
/