Set of values in pl/pgsql
I'm writing some pl/pgsql code in postgres - and have come up to this issue. Simplified, my code looks like this:
declare
resulter mytype%rowtype;
...
for resulter in
select id, [a lot of other fields]
from mytable [joining a lot of other tables]
where [some reasonable where clause]
loop
if [certain condition on the resulter] then
[add id to a set];
end if;
return next resulter;
end loop;
select into myvar sum([some field])
from anothertable
where id in ([my set from above])
The question is around the [add to set]. In another scenario in the past, I used to deal with it this way:
declare
myset varchar := '';
...
loop
if [condition] then
myset || ',' || id;
end if;
return next resulter;
end loop;
execute 'select sum([field]) from anothertable where id in (' || trim(leading ',' from myset) || ')' into myvar
However this doesn't seem too efficient to me when the number of id's to be added to this set is large. What other options do I have for ke开发者_Go百科eping track of this set and then using it?
-- update --
Obviously, another option is to create a temporary table and insert ids into it when needed. Then in the last select statement have a sub-select on that temporary table - like so:
create temporary table x (id integer);
loop
if [condition] then
insert into x values (id);
end if;
return next resulter;
end loop;
select into myvar sum([field]) from anothertable where id in (select id from x);
Any other options? Also, what would be the most efficient, considering that there may be many thousands of relevant ID's.
In my opinion, temp tables are the most efficient way to handle this:
create temp table x(id integer not null primary key) on commit drop;
精彩评论