0

I want to know if it's posible to do something like this:

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$

i would appreciate any response! thanks!

1 Answer 1

1

A loop is typically not very efficient, use unnest() and insert the result in a single query:

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$

You can however loop through an array 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;

That will be a lot slower though.

Sign up to request clarification or add additional context in comments.

1 Comment

"desc" and "array" are reserved words and should be quoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.