ALTER FUNCTION "dba"."get_arvesaaja_meil"( in a_asutnr integer, in a_saajanr integer, in a_send_mail smallint default 0 )
returns char(50)
BEGIN
  declare ls_return char(50);
  if exists(select 1 from dk_konfm where dk_konfm.id=1 and dk_konfm.yld_arve_saajale=1) then
    if a_send_mail=0 then
      select if eakchannel is not null and eakchannel=5 and asulist.meil2 is not null and Length(asulist.meil2)>0 then asulist.meil2 else (if eakchannel is not null and eakchannel=3 and asulist.meil is not null and Length(asulist.meil)>0 then asulist.meil else (if asulist.meil is not null and Length(asulist.meil)>0 then asulist.meil else asulist.meil2 endif) endif) endif into ls_return from asulist where asulist.asutnr=a_saajanr;
    else
      select if eakchannel is not null and eakchannel=5 and asulist.meil2 is not null and Length(asulist.meil2)>0 then asulist.meil2 else if eakchannel is not null and eakchannel=3 and asulist.meil is not null and Length(asulist.meil)>0 then asulist.meil endif endif into ls_return from asulist where asulist.asutnr=a_saajanr;
    end if;
  end if;
  if ls_return is null or Length(Trim(ls_return))=0 then
    if a_send_mail=0 then
      select if eakchannel is not null and eakchannel=5 and asulist.meil2 is not null and Length(asulist.meil2)>0 then asulist.meil2 else (if eakchannel is not null and eakchannel=3 and asulist.meil is not null and Length(asulist.meil)>0 then asulist.meil else (if asulist.meil is not null and Length(asulist.meil)>0 then asulist.meil else asulist.meil2 endif) endif) endif into ls_return from asulist where asulist.asutnr=a_asutnr;
    else
      select if eakchannel is not null and eakchannel=5 and asulist.meil2 is not null and Length(asulist.meil2)>0 then asulist.meil2 else if eakchannel is not null and eakchannel=3 and asulist.meil is not null and Length(asulist.meil)>0 then asulist.meil endif endif into ls_return from asulist where asulist.asutnr=a_asutnr;
    end if;
  end if;
  if ls_return is null or Length(Trim(ls_return))=0 then
    set ls_return=''
  end if;
  return ls_return;
END