0

如果我有,我该如何迭代 integer[]:
operators_ids = string_to_array(operators_ids_g,',')::integer[];
我想要迭代operators_ids.
我不能这样做:
FOR oid IN operators_ids LOOP
这:
FOR oid IN SELECT operators_ids LOOP
oidinteger

4

2 回答 2

1

您可以遍历一个数组,例如

DO
$body$
DECLARE your_array integer[] := '{1, 2, 3}'::integer[];
BEGIN
    FOR i IN array_lower(your_array, 1) .. array_upper(your_array, 1)
    LOOP

    -- do something with your value
    raise notice '%', your_array[i];

    END LOOP;
END;
$body$
LANGUAGE plpgsql;

但在我看来,主要问题是:为什么需要这样做?您有机会以更好的方式解决问题,例如:

DO
$body$
DECLARE i record;
BEGIN
    FOR i IN (SELECT operators_id FROM your_table)
    LOOP

    -- do something with your value
    raise notice '%', i.operators_id;

    END LOOP;
END;
$body$
LANGUAGE plpgsql;
于 2012-12-18T12:05:41.047 回答
0

我认为德索是对的。您不需要使用索引来循环数组。如果您根据 person_id 结合限制 1 进行选择语句分组,您将获得所需的结果集:

create or replace function statement_example(p_data text[]) returns int as $$
declare
 rw event_log%rowtype;
begin
  for rw in select * from "PRD".events_log where (event_type_id = 100 or event_type_id = 101) and person_id = any(operators_id::int[]) and plc_time < begin_date_g order by plc_time desc group by person_id limit 1 loop
  raise notice 'interesting log: %', rw.field;
  end loop;
  return 1;
end;
$$ language plpgsql volatile;

那应该表现得更好。如果您仍然喜欢循环一个整数数组并且有很多 person_ids 需要照顾,那么您是否可以考虑使用享元设计模式:

create or replace function flyweight_example(p_data text[]) returns int as $$
declare
 i_id int;
 i_min int;
 i_max int;
begin
 i_min := array_lower(p_data,1);
 i_max := array_upper(p_data,1);
 for i_id in i_min .. i_max loop
  raise notice 'interesting log: %',p_data[i_id];
 end loop;
 return 1;
end;
$$ language plpgsql volatile;
于 2012-12-18T19:05:46.503 回答