在Firebird SQL存储过程中,我在'for do'循环中使用'select into',我找不到pg函数的等价物。
for select purchase.quantity, purchase.purchasevalue, purchase.purchased, purchase.id from purchase
join cellarbook cb on purchase.fk_cellarbook_id = cb.id
join bottle bot on cb.fk_bottle_id = bot.id
where bot.id = :bottleid
order by purchase.purchased ASC
into :purquantity, :purvalue, :purdate, :purid
do
begin
/* calculate quantity on hand at point of purchase
here come some more 'select' and calculations and
then and 'update' */
select sum(psum.quantity) as purquantitysum from purchase
join cellarbook cb on psum.fk_cellarbook_id = cb.id
join bottle bot on cb.fk_bottle_id = bot.id
where bot.id = bottleid and psum.purchased <= pur.purchased and psum.id <> pur.id
into :purquantitysum
end
我认为这是'for in loop'但是我对“选择进入”的等效内容感兴趣。
答案 0 :(得分:1)
您需要为此使用记录变量:
declare
r record;
begin
for r in
select col_1, col_2 from some_table;
loop
select sum(x)
from other_table
where id = r.col_1;
end loop;
end;
当你在循环中运行update
或select
语句时,通常是代码嗅觉(“逐行处理”)。在大多数情况下,在单个语句中对所有内容进行批量处理要高效得多。
答案 1 :(得分:0)
我使用光标。有相同主题的几种变体。我通常用这个:
declare mycursor cursor for select a, b from c;
declare d, e bigint;
begin
loop
fetch from mycursor into d, e
exit when not found;
-- do your thing here
end loop;
close mycursor;
-- maybe do some other stuff
end;