PostgreSQL-数组作为函数参数

时间:2018-07-09 19:12:42

标签: arrays postgresql plpgsql

我想知道是否可以做这样的事情:

CREATE OR REPLACE function my_funct(some_data some_type, array int[])
RETURNS TABLE(code int, desc varchar)
LANGUAGE plpgsql
as $function$
DECLARE
  ..
BEGIN
 WHILE some_condition < array.size --i know this doesn't exists 
  LOOP
  INSERT INTO some_table values(array_data[1]); --I want to insert data from 
the array as long as it has data
  END LOOP;
  RETURN QUERY select 1001, cast ('DONE!' as varchar);
END;
$function$

我将不胜感激! 谢谢!

1 个答案:

答案 0 :(得分:1)

循环通常效率不高,请使用unnest()并将结果插入单个查询中:

CREATE OR REPLACE function my_funct(some_data some_type, array_data int[])
RETURNS TABLE(code int, descr varchar)
LANGUAGE plpgsql
as $function$
DECLARE
  ..
BEGIN
  INSERT INTO some_table 
  select d.x
  from unnest(array_data) as d(x);

  RETURN QUERY select 1001, 'DONE!';
END;
$function$

不过,您可以遍历数组as documented in the manual

BEGIN
  FOREACH x IN ARRAY array_data
  LOOP
    INSERT INTO some_table  values (x);
  END LOOP;
  RETURN QUERY select 1001, 'DONE!';
END;

那会慢很多。