CREATE FUNCTION "DBA"."get_eak_earve_saajanr"( in a_id_dk_earve integer )
RETURNS INTEGER
BEGIN
  declare ll_saajanr integer;
  declare ls_regnumber char(11);
  declare ls_name char(50);
  declare ls_code char(9);
  select if (dk_earve.sisse is null or dk_earve.sisse=0) then
           if dk_costreport."id" is null then
             if dk_earve.maksjaname is null and (dk_earve.paytoname is null or Length(Trim(dk_earve.paytoname))=0 or dk_earve.paytoname=dk_earve.sellername) then
               null
             else
               if dk_earve.paytoname is null or Length(Trim(dk_earve.paytoname))=0 then
                 get_eak_asutnr(Left(dk_earve.maksjaregnumber,11),Left(dk_earve.maksjaname,50), Left(Trim(dk_earve.maksjacode),9))
               else
                 get_eak_asutnr('',Left(dk_earve.paytoname,50), '')
               endif
             endif
           else
             if dk_costreport.maksjaname is null or Length(Trim(dk_costreport.maksjaname))=0 or dk_costreport.maksjaname=dk_costreport.sellername then
               null
             else
               get_eak_asutnr(Left(dk_costreport.maksjaregnumber,11),Left(dk_costreport.maksjaname,50), Left(Trim(dk_costreport.maksjacode),9))
             endif
           endif
         else
           null
         endif
    into ll_saajanr
    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;
  return ll_saajanr;
END