create or replace procedure sp_fco_ins_pi_pens_proc(pch_compania char,
                                                    psi_anio     number,
                                                    pti_mes      number,
                                                    pch_sucursal char /* '0'. todas, ''. consolidado */) as
  /*************************************************************************/
  -- modulo fiscal colombiano 2.0 adam v3
  -- descripcion: alta de procesos de planilla integrada pensionados
  -- autor: Manuel Daza
  -- fecha: noviembre 2006
  -- revisiones:
  /*************************************************************************/
  dummy number(1) := 0;

begin
  if pch_sucursal = '0' then
    insert into fco_pi_pens_proc
      (compania, anio, mes, sucursal, procesar)
      select pch_compania, psi_anio, pti_mes, s.sucursal, 0
        from vw_fco_sucursales s
       where compania = pch_compania
         and nvl(s.autoliquida, 1) = 1
         and not exists (select 1
                from fco_pi_pens_proc x
               where x.compania = pch_compania
                 and x.anio = psi_anio
                 and x.mes = pti_mes
                 and x.sucursal = s.sucursal);
  else
    begin
      select 1
        into dummy
        from fco_pi_pens_proc
       where compania = pch_compania
         and anio = psi_anio
         and mes = pti_mes
         and nvl(sucursal, ' ') = nvl(pch_sucursal, ' ');
    exception
      when no_data_found then
        insert into fco_pi_pens_proc
          (compania, anio, mes, sucursal, procesar)
        values
          (pch_compania, psi_anio, pti_mes, nvl(pch_sucursal, ' '), 0);
      
        return;
    end;
    raise_application_error(-21000,
                            'el registro a insertar en [fco_pi_pens_proc] ya existe');
  end if;
end sp_fco_ins_pi_pens_proc;
/
