知道我在这里做错了吗?
CREATE OR REPLACE FUNCTION update_prices_in_ord1( ) RETURNS void AS $$
DECLARE
cur CURSOR for select ord2.ord1_id, sum(ord2.price*ord2.qty) as totprice from ord2 group by ord1_id;
--tmpid int;
--tmpid ord2.ord1_id%TYPE;
--tmpprice float;
mydata RECORD;
BEGIN
open cur;
loop
--fetch cur into tmpid,tmpprice;
fetch cur into mydata;
--raise notice 'price=%, id=%', tmpprice, tmpid;
raise notice 'price=%, id=%', mydata.totprice, mydata.ord1_id;
update ord1 set price=mydata.totprice where id=mydata.ord1_id;
end loop;
close cur;
END;
$$ LANGUAGE plpgsql;
正如你所看到的,我已经尝试了一些选项(在评论中),但没有运气。 我得到的只是无限空:
NOTICE: price=<NULL>, id=<NULL>
如果我单独运行游标的sql就运行正常:
testdb=# select ord2.ord1_id, sum(ord2.price*ord2.qty) as totprice from ord2 group by ord1_id;
ord1_id | totprice
---------+----------
14 | 10
27 | 42.5
17 | 57.5
28 | 43
15 | 142
...
我想要做的就是根据以上总价更新ord1.price字段,以匹配ord1.id。
非常感谢!
答案 0 :(得分:1)
您已经编写了无条件循环。由于没有exit
或return
语句,它永远不会停止。
for
loop为您解决此问题。最重要的是,它将自动打开,获取和关闭光标:
BEGIN
for mydata in cur loop
raise notice 'price=%, id=%', mydata.totprice, mydata.ord1_id;
update ord1 set price=mydata.totprice where id=mydata.ord1_id;
end loop;
END;
但是,您不需要循环来执行此操作;您应该能够在纯SQL中编写此update
:
update ord1
set price = total.totprice
from (select ord1_id, sum(price*qty) as totprice from ord2 group by ord1_id) total
where ord1.id = total.ord1_id