CREATE FUNCTION "DBA"."get_eak_invoicesum"( in a_id_dk_earve integer, in a_id_dk_earve_sum integer )
RETURNS decimal(20,2)
BEGIN
  declare ldc_return decimal(20,2);
  declare ldc_summa decimal(20,2);
  declare ldc_discount decimal(20,2);
  declare ldc_sumbeforevat decimal(20,2);
  declare ldc_totalvatsum decimal(20,2);
  set ldc_return=0;
  set ldc_summa=0;
  set ldc_discount=get_eak_invoicediscount(a_id_dk_earve, a_id_dk_earve_sum);
  set ldc_sumbeforevat=get_eak_sumbeforevat(a_id_dk_earve, a_id_dk_earve_sum);
  set ldc_totalvatsum=get_eak_totalvatsum(a_id_dk_earve, a_id_dk_earve_sum);
  select (if ldc_sumbeforevat=0 then (if (totalsum is null or totalsum=0) then invoicesum+ldc_discount else totalsum-ldc_totalvatsum endif) else ldc_sumbeforevat endif) into ldc_summa from "dk_earve_sum" where "dk_earve_sum"."id_dk_earve"=a_id_dk_earve and "dk_earve_sum"."id"=a_id_dk_earve_sum;
  if ldc_summa is not null then
    set ldc_return=ldc_return+ldc_summa
  end if;
  set ldc_summa=0;
  select "dk_earve_sum"."rounding" into ldc_summa from "dk_earve_sum" where "dk_earve_sum"."id_dk_earve"=a_id_dk_earve and "dk_earve_sum"."id"=a_id_dk_earve_sum;
  if ldc_summa is not null then
    set ldc_return=ldc_return+ldc_summa
  end if;
  return ldc_return;
END