ALTER FUNCTION "DBA"."get_eak_transactiondate"( in a_id_dk_earve integer default 0, in a_id_dk_earve_rida integer default 0 )
RETURNS date
BEGIN
  declare ld_kuup date;
  set ld_kuup=null;
  if a_id_dk_earve>0 and a_id_dk_earve_rida>0 then
    select if dk_earve_rida.accountingdate is null or dk_earve_rida.accountingdate<ymd(2000,1,1) then null else dk_earve_rida.accountingdate endif into ld_kuup from dk_earve_rida where dk_earve_rida.id_dk_earve=a_id_dk_earve and dk_earve_rida.id=a_id_dk_earve_rida
  end if;
  if (ld_kuup is null or ld_kuup<ymd(2000,1,1)) and a_id_dk_earve>0 then
    select kuup into ld_kuup from dk_earve where dk_earve.id=a_id_dk_earve;
    if ld_kuup is null or ld_kuup<ymd(2000,1,1) then
      select first cast(text3 as date) into ld_kuup from dk_earve_ext where id_dk_earve=a_id_dk_earve and text1='eakTransactionDate'
    end if;
    if ld_kuup is null or ld_kuup<ymd(2000,1,1) then
      select if dk_costreport.invoicedate is null then dk_earve.invoicedate else dk_costreport.invoicedate endif into ld_kuup from dk_earve left outer join dk_costreport on dk_earve.id_dk_costreport=dk_costreport."id" where dk_earve."id"=a_id_dk_earve;
    end if;
  end if;
  if ld_kuup is null or ld_kuup<ymd(2000,1,1) then
    set ld_kuup=Now()
  end if;
  return ld_kuup;
END