IF OBJECT_ID('dbo.sp_fco_ins_pi_pens_proc') IS NOT NULL
    DROP PROCEDURE dbo.sp_fco_ins_pi_pens_proc 
GO
CREATE PROCEDURE dbo.sp_fco_ins_pi_pens_proc
(
    @pch_compania char(4),
    @psi_anio smallint,
    @pti_mes tinyint,
    @pch_sucursal char(10) /* '0'. Todas, ''. Consolidado */
)
AS
/*************************************************************************/
-- Modulo Fiscal Colombiano 2.0 ADAM V3
-- Descripcion: Alta de Procesos de Planilla Integrada Pensionados
-- Autor: Juan Carlos Leguizamon
-- Fecha: Julio 2006
-- Revisiones:
/*************************************************************************/
BEGIN
    IF @pch_sucursal = '0'
    BEGIN
        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 ISNULL(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)
    END
    ELSE
    BEGIN
        IF EXISTS(SELECT 1 FROM fco_pi_pens_proc 
                  WHERE compania = @pch_compania AND anio = @psi_anio 
                    AND mes = @pti_mes AND sucursal = @pch_sucursal)
        BEGIN
            RAISERROR ('El registro a insertar en [fco_pi_pens_proc] ya existe', 16, 1)
            RETURN
        END
        INSERT INTO fco_pi_pens_proc (compania, anio, mes, sucursal, procesar)
        SELECT @pch_compania, @psi_anio, @pti_mes, @pch_sucursal, 0
    END
END
GO
GRANT EXECUTE ON dbo.sp_fco_ins_pi_pens_proc TO PUBLIC
GO
