postgresql中的if-inside for循环

postgresql中的if-inside for循环,postgresql,for-loop,if-statement,Postgresql,For Loop,If Statement,我有两张桌子,如下所示 TABLE 1 TABLE 2 -------- -------- id id date table1_id total subtotal balance table 1 table 2 -------- --------- id total balance id table1_id subtot

我有两张桌子,如下所示

TABLE 1       TABLE 2
--------     --------
id            id
date          table1_id
total         subtotal
balance

table 1                     table 2
--------                    ---------
id  total  balance          id table1_id subtotal paid
1    20      10              1      1      5       5  
2    30      30              2      1      15      5
                             3      2      10      0
                             4      2      10      0
                             5      2      10      0
我必须在表2中增加付费栏。所以,谁能帮我为现有数据向新添加的列添加值呢。我试着写下面的程序,但因为postgres不允许,所以我不能这样做

CREATE OR REPLACE FUNCTION public.add_amountreceived_inbillitem() RETURNS void AS
$BODY$
DECLARE 
rec RECORD;
inner_rec RECORD;
distributebalance numeric;
tempvar numeric;
BEGIN
FOR rec IN select * from table1 
LOOP 
distributebalance = rec.balance;
FOR inner_rec IN(select * from table2 where table1_id = rec.id order by id limit 1) 
 tempvar = distributebalance - inner_rec.subtotal;
 if (distributebalance >0 and tempvar>=0) THEN 
    update table2 set paid = inner_rec.subtotal where id = inner_rec.id ;
    distributebalance =distributebalance-inner_rec.subtotal;
 else if( distributebalance >0 and tempvar<0 )THEN 
    update table2 set paid = distributebalance where id = inner_rec.id;
END IF;
END LOOP; 
END LOOP;
END; $BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

提前感谢:

Postgres允许循环中使用IF语句

问题是,如果你已经开始了一个新的IF语句,那么通过编写ELSE,你现在有两个开始的IF,但只有一个结束IF。plpgsql中正确的elseif是ELSIF或elseif。因此,只要删除这些单词之间的空格,它就会起作用