create or replace procedure adam.sp_fco_pi_tot_icbf(p_compania in char,
                                                    p_anio     in number,
                                                    p_mes      in number,
                                                    p_sucursal in char,
                                                    p_tipo_planilla in char) is
  v_rec_rt08 fco_integrada_rt08%rowtype;

  cursor c1(c_compania char, c_anio number, c_mes number, c_sucursal char, c_tipo_planilla char) return fco_integrada_rt08%rowtype is
    select compania,
           anio,
           mes,
           nvl(c_sucursal, ' ') sucursal,
           c_tipo_planilla tipo_planilla,
           1 secuencia,
           '899999239' nit,
           '2' dv,
           sum(nvl(aporte_icbf, 0)) valor,
           0,
           0,
           null,
           count(*) nro_personas
      from fco_integrada_det
     where compania = c_compania
       and anio = c_anio
       and mes = c_mes
       and (sucursal = c_sucursal or c_sucursal is null)
       and tipo_planilla = c_tipo_planilla
       and nvl(aporte_icbf, 0) <> 0
     group by compania, anio, mes;

begin

  open c1(p_compania, p_anio, p_mes, p_sucursal, p_tipo_planilla);
  loop
    fetch c1
      into v_rec_rt08;
    exit when c1%notfound;
    insert into fco_integrada_rt08 values v_rec_rt08;
  end loop;
  close c1;

end sp_fco_pi_tot_icbf;
/
