I need to create a function that compute account sum for each branch and compare to branch balance.
I tried to do this:
CREATE OR REPLACE FUNCTION t3() RETURNS TABLE(bb integer, sum integer) AS $$
BEGIN
FOR i IN 1..50 LOOP
BEGIN
SELECT bbalance FROM branch WHERE branchid = i
union
SELECT sum(balance) FROM account WHERE branch = i;
END;
END LOOP;
END;
$$ LANGUAGE plpgsql;
I'm kinda confused right now... I would like it to return a table with 2 columns: one with the value of bbalance from the branch; the second one with the sum of every balance in that branch.
I need something that I can call with select * from t3()
.
That's what I write in pgAdmin query editor:
CREATE OR REPLACE FUNCTION t3() RETURNS TABLE(bb integer, sum integer) AS $$
DECLARE
bal integer;
BEGIN
FOR i IN SELECT branchid FROM branch
LOOP
SELECT INTO bb bbalance FROM branch WHERE branchid = i;
SELECT INTO "sum" sum(balance) FROM account WHERE branch = i;
RETURN NEXT;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
And the error is:
ERRORE: variabile del ciclo sulle righe deve essere una variabile di tipo row o record o una lista di variabili scalari
LINE 5: FOR i IN SELECT branchid FROM branch
^
********** Error **********
ERRORE: variabile del ciclo sulle righe deve essere una variabile di tipo row o record o una lista di variabili scalari
SQL state: 42601
Character: 119
Italian - translation is:
loop variable of loop over rows must be a record or row variable or list of scalar variables.
SET lc_messages = 'C';
in your session to get English error messages. – Erwin Brandstetter Jul 30 at 0:18