IF OBJECT_ID('dbo.fn_fco_acum_ani') IS NOT NULL
    DROP FUNCTION dbo.fn_fco_acum_ani
GO
CREATE FUNCTION dbo.fn_fco_acum_ani
(
    @pvc_parametro varchar(10),
    @pti_secuencia tinyint,
    @pch_compania char(4),
    @psi_anio smallint,
    @pch_trabajador char(10)
)
RETURNS decimal(19,6)
AS
BEGIN
    DECLARE 
        @vti_tip_rtf tinyint,
        @vsi_cnc_rtf smallint,
        @vch_agr_rtf char(3),
        @vdc_rtf decimal(19,6)
        
    SELECT @vti_tip_rtf = tipo FROM vw_fdt_parametros
    WHERE compania = @pch_compania AND parametro = @pvc_parametro AND secuencia = @pti_secuencia

    IF @vti_tip_rtf = 0
        SELECT @vsi_cnc_rtf = dato, @vch_agr_rtf = '' FROM vw_fdt_parametros
        WHERE compania = @pch_compania AND parametro = @pvc_parametro AND secuencia = @pti_secuencia
    ELSE
        SELECT @vsi_cnc_rtf = 0, @vch_agr_rtf = dato FROM vw_fdt_parametros
        WHERE compania = @pch_compania AND parametro = @pvc_parametro AND secuencia = @pti_secuencia
    
    SELECT @vdc_rtf =
        acum_imp_mes_01 + acum_imp_mes_02 + acum_imp_mes_03 + acum_imp_mes_04 +
        acum_imp_mes_05 + acum_imp_mes_06 + acum_imp_mes_07 + acum_imp_mes_08 +
        acum_imp_mes_09 + acum_imp_mes_10 + acum_imp_mes_11 + acum_imp_mes_12
    FROM acumulados_mensuales
    WHERE compania = @pch_compania
      AND trabajador = @pch_trabajador
      AND agr_conceptos = @vch_agr_rtf
      AND concepto = @vsi_cnc_rtf
      AND anio = @psi_anio

    RETURN IsNull(@vdc_rtf, 0)
END
GO
GRANT EXECUTE ON dbo.fn_fco_acum_ani TO PUBLIC
GO
