CREATE FUNCTION [PLANTA_F_CALC_PERIOD_FACTOR]
( 
   @p_units_day NUMERIC(8, 2),
   @p_calculation NUMERIC(8, 2) = 0,
   @p_val       NUMERIC(8, 2) = 0, 
   @p_unit    VARCHAR(2) = 'h', 
   @p_factor_bu  NUMERIC(8, 2) = 1
)
RETURNS NUMERIC(8, 2)
AS 
BEGIN		   
	DECLARE
         @v_result       NUMERIC(8, 2),
         @value_hrs       NUMERIC(8, 2),
         @calculationtype NUMERIC(8, 2),
          -- Default Values, in case parameters are NULL
         @units_day       NUMERIC(8, 2)      = 8,
         @calculation     NUMERIC(1)   = 0,
         @val           NUMERIC(8,2) = 0,
         @unit        VARCHAR(2)   = 'h',
         @factor_bu      NUMERIC(8,2) = 1
	
    -- overwrite Default Values, if parameter values are provided
    if @p_units_day is not null 
    begin 
        set @units_day = @p_units_day;
    end
    
    if @p_calculation is not null
    begin
        set @calculation = @p_calculation;
    end
        
    if @p_val is not null
    begin
        set @val = @p_val;
    end
    
    if @p_unit is not null
    begin
        set @unit = @p_unit;
    end
    
    if @p_factor_bu is not null
    begin
        set @factor_bu = @p_factor_bu;
    end
    
    --------------------------------------------
    
    if @unit = 'h' or @unit = 'T'
    begin
        set @value_hrs = @val * @factor_bu;
    end
    else
    begin
        set @value_hrs = @val / 100 * @units_day;
    end
    
    if @calculation = 0
    begin
        set @calculationtype = 1;
    end
    else
    begin
        set @calculationtype = -1;
    end
    
    set @v_result = (@value_hrs * @calculationtype)
    
	RETURN @v_result

END