postgresql7.1
declare
i integer;
row RECORD;
begin
select max(sort_key)
into i
from portal_element_map
where region = :region
if NOT FOUND then
i := 1
end if;
for row in (select element_id
from portal_element_map
where $where
order by region, sort_key) loop
insert into portal_element_map (sort_key, region, portal_id, element_id)
values (i, :region, :portal_id, row.element_id);
i := i + 1;
end loop;
end;