ALTER PROCEDURE "DBA"."delete_pa_yksus"( in a_skoop integer )
BEGIN
  declare ll_yksusnr integer;
  declare err_notfound exception for sqlstate value '02000';
  declare c_pa_yksus insensitive cursor for select pa_yksus.yksusnr from pa_yksus where (pa_yksus.skoop=a_skoop or a_skoop=0);
  open c_pa_yksus;
  pa_yksus_loop: loop
    fetch next c_pa_yksus into ll_yksusnr;
    if sqlstate = err_notfound then
      leave pa_yksus_loop
    end if;
    if not exists(select 1 from pa_paryld where yksusnr=ll_yksusnr) then
      if not exists(select 1 from pa_reserv where yksusnr=ll_yksusnr) then
        if not exists(select 1 from pa_tasu where yksusnr=ll_yksusnr) then
          if not exists(select 1 from pl_resdef where yksusnr=ll_yksusnr) then
            delete from pa_isik where pa_isik.yksusnr=ll_yksusnr;
            if not exists(select 1 from pa_erisood where yksusnr=ll_yksusnr) then
              if not exists(select 1 from pa_plnr where yksusnr=ll_yksusnr) then
                if not exists(select 1 from pl_resdef where yksusnr=ll_yksusnr) then
                  delete from pa_yksus where pa_yksus.yksusnr=ll_yksusnr;
                end if
              end if
            end if
          end if
        end if
      end if
    end if
  end loop pa_yksus_loop;
  close c_pa_yksus
END