ALTER FUNCTION "DBA"."get_pv_min_id"( in a_id integer )
RETURNS INTEGER
BEGIN
  declare li_id integer;
  declare ls_toot_nr char(20);
  declare ll_skoop integer;
  if a_id is null or a_id=0 then
    set li_id=0
  else
	select "pv_kanne"."toot_nr","pv_yksus"."skoop"
		into ls_toot_nr,ll_skoop
		from "pv_kanne" left outer join "pv_yksus" on "pv_kanne"."yksusnr"="pv_yksus"."yksusnr"
		where "pv_kanne"."id"=a_id;
    if ls_toot_nr is null or Length(Trim(ls_toot_nr))=0 then
      set li_id=a_id
    else
      select first "pv_kanne"."id"
		into li_id
		from "pv_kanne" left outer join "pv_yksus" on "pv_kanne"."yksusnr"="pv_yksus"."yksusnr"
		where "pv_kanne"."toot_nr"=ls_toot_nr and "pv_yksus"."skoop"=ll_skoop
		order by "pv_kanne"."id" ASC;
    end if;
  end if;
  return li_id;
END