Thursday, September 15, 2016

BST operation using P/L SQL

create or replace function accumbst()
    returns void as $$
declare
    currentValue int;
    accumulatedValue int;
    cr cursor is
        select id, parentId, value from testbst
        order by id desc;   
    rw testbst%rowtype;
begin
    delete from testreportbst;   
    open cr;
    <<loop1>>
    loop
        fetch cr into rw;
        exit when not found;
        insert into testreportbst values(rw.id, rw.parentId, rw.value);
    end loop loop1;

    close cr;
    open cr;

    <<loop2>>   
    loop
        fetch cr into rw;
        exit when not found;
        select value into currentValue from testreportbst where id = cast(rw.id as text);
        select value into accumulatedValue from testreportbst where id = cast(rw.parentId as text);
        accumulatedValue := accumulatedValue + currentValue;
        update testreportbst set value = accumulatedValue where id = cast(rw.parentId as text);
    end loop loop2;      
    close cr;
end $$ language plpgsql;

No comments:

Post a Comment