'PL/pgSQL user-defined-function for update a list of data

I am written a user-defined-function using PL/pgSQL given below:

CREATE OR REPLACE FUNCTION update_balance(id_input varchar, amount_input dec)
RETURNS TABLE (d_id varchar, d_parent_id varchar, d_balance dec) AS $$
DECLARE
    d_id varchar;
    d_parent_id varchar;
    d_balance dec;
BEGIN
    SELECT gl.id, gl.parent_id, gl.balance
    INTO d_id, d_parent_id, d_balance
    FROM gl
    WHERE gl.id = id_input;
    
    UPDATE gl
    SET balance = d_balance + amount_input
    WHERE gl.id = id_input;
    
    WHILE d_parent_id IS NOT NULL LOOP      
        SELECT gl.id, gl.parent_id, gl.balance
        INTO d_id, d_parent_id, d_balance
        FROM gl
        WHERE gl.id = d_parent_id;
        
        UPDATE gl
        SET balance = d_balance + amount_input
        WHERE gl.id = d_parent_id;

        d_balance := 0;
    END LOOP;
END
$$ LANGUAGE plpgsql;

And my data set looks like below:

{'id':1,'parent_id':NULL,'balance':0.0}
{'id':4,'parent_id':1,'balance':0.0}
{'id':14,'parent_id':4,'balance':0.0}
{'id':25,'parent_id':14,'balance':0.0}
{'id':120,'parent_id':25,'balance':0.0}

After this, I called the function below:

SELECT update_balance('120', 100.0);

After this, the result looks like below:

{'id':1,'parent_id':NULL,'balance':300.0}
{'id':4,'parent_id':1,'balance':200.0}
{'id':14,'parent_id':4,'balance':100.0}
{'id':25,'parent_id':14,'balance':0.0}
{'id':120,'parent_id':25,'balance':100.0}

ID 25 updated, which is fine, ID 14 didn't update, which is not fine, ID 4 updated, which is fine, ID 1 updated twice, which is not fine.

I don't understand why this is happening. I need to know why this is happening and to prevent this.

My expected result is, after calling the function update_balance() ID 120, 25, 14, 4, 1's balance will be plus 100 with it's current balance.

As I noticed I called the function to sum value 100 with current balance, but it's sum value multiplying every time once.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source