Mostrando entradas con la etiqueta Asset Fixed. Mostrar todas las entradas
Mostrando entradas con la etiqueta Asset Fixed. Mostrar todas las entradas

miércoles, 16 de octubre de 2019

Get Accumulated Depreciation in PostgreSQL Function

-- select * from fnt_get_depreciation_acum('20190620', '20190930', 244685.29, 10);

-- select * from tmp_asset_periods;

create or replace function fnt_get_depreciation_acum(p_activationdate date, p_enddate date, p_asset_value numeric(20,2), p_uselifeyears numeric(10,2))
returns numeric(20,2)
as $$
declare
    v_depreciation_value numeric(20,2) = 0.00;
    v_qty_period int = (p_uselifeyears * 12);
   
    v_dep_date date = p_activationdate;
    v_yearno int = 0;
    v_monthno int = 0;

    v_enddate date = p_enddate;
    v_current_year int = 0;
    v_current_month int = 0;

    v_current_period int = 0;
    v_depreciation_acum numeric(20,2) = 0.00;
    v_current_dep_acum numeric(20,2) = 0.00;
begin
    v_depreciation_value =
    coalesce((
        p_asset_value / v_qty_period
    ), 0.00);

    drop table if exists tmp_asset_periods;

    create temporary table tmp_asset_periods
    as
    select
        1::int periodno,
        now()::date as dep_date,
        0.00::numeric(20,2) as dep_amt,
        0.00::numeric(20,2) as dep_acum;
   
    truncate table tmp_asset_periods;

    for k in 1..v_qty_period loop
        v_yearno = extract(year from v_dep_date);
        v_monthno = extract(month from v_dep_date);
   
        v_current_year = extract(year from v_enddate);
        v_current_month = extract(month from v_enddate);
       
        if(k = v_qty_period)then
            v_depreciation_value = p_asset_value - v_depreciation_acum;
        end if;
   
        v_depreciation_acum = v_depreciation_acum + v_depreciation_value;
       
        insert into tmp_asset_periods
        select
            k,
            v_dep_date,
            v_depreciation_value,
            v_depreciation_acum;
       
        v_dep_date = p_activationdate + (k::varchar || ' month'::varchar)::interval;
       
        if((v_yearno = v_current_year) and (v_monthno = v_current_month))then
            v_current_period = k;
            v_current_dep_acum = v_depreciation_acum;
        end if;
    end loop;

    return v_current_dep_acum;
end;
$$ language plpgsql;

Get Depreciation Value in PostgreSQL Function

-- select * from fnt_get_depreciation_value(255544, 5);

create or replace function fnt_get_depreciation_value(p_asset_value numeric(20,2), p_uselifeyears numeric(10,2))
returns numeric(20,2)
as $$
declare
    v_depreciation_value numeric(20,2) = 0.00;
begin
   
    if(p_uselifeyears > 0)then
        v_depreciation_value =
        coalesce((
            p_asset_value / (p_uselifeyears * 12)
        ), 0.00);
    else
        v_depreciation_value = 0;
    end if;
   
    return v_depreciation_value;
end;
$$ language plpgsql;