-- 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;
No hay comentarios:
Publicar un comentario