ALTER PROCEDURE "DBA"."pr_autoimp"( )
BEGIN
  declare li_kuu smallint;
  declare li_aasta smallint;
  declare li_fikskuu smallint;
  declare li_fiksaasta smallint;
  declare ll_skoop integer;
  declare li_id_prog smallint;
  declare ld_peralg date;
  declare ld_perlop date;
  declare err_notfound exception for sqlstate value '02000';
  declare c_pr_import dynamic scroll cursor for
    select pr_import.kuu,pr_import.aasta,pr_import.skoop,pr_import.id_prog
      from pr_import
      where pr_import.aasta>li_fiksaasta or (pr_import.aasta=li_fiksaasta and pr_import.kuu>li_fikskuu);
  select month(pr_konfm.yld_fikskuup),years(pr_konfm.yld_fikskuup) into li_fikskuu,li_fiksaasta from pr_konfm where id=1;
  if month(today())>6 then
    if li_fiksaasta<years(today()) then
      set li_fiksaasta=years(today())-1;
      set li_fikskuu=12
    end if
  else
    if li_fiksaasta<years(today())-1 then
      set li_fiksaasta=years(today())-2;
      set li_fikskuu=12
    end if
  end if;
  open c_pr_import;
  pr_import_loop: loop
    fetch next c_pr_import into li_kuu,li_aasta,ll_skoop,li_id_prog;
    if sqlstate = err_notfound then -- kui eof
      leave pr_import_loop
    end if;
    set ld_peralg=ymd(li_aasta,li_kuu,1);
    set ld_perlop=get_perlop(ld_peralg);
    case li_id_prog when 1 then
      call pr_kp_kan(ll_skoop,ld_peralg,ld_perlop)
    when 2 then
      call pr_dk_kan(ll_skoop,ld_peralg,ld_perlop)
    when 5 then
      call pr_pa_kan(ll_skoop,ld_peralg,ld_perlop)
    when 6 then
      call pr_pv_kan(ll_skoop,ld_peralg,ld_perlop)
    when 7 then
      call pr_mt_kan(ll_skoop,ld_peralg,ld_perlop)
    end case;
    call pr_import_delete(ll_skoop,ld_peralg,ld_perlop,'uuspm',li_id_prog,0);
    call pr_kan_update(ll_skoop,ld_peralg,ld_perlop,li_id_prog)
  end loop pr_import_loop;
  close c_pr_import;
  commit
END