0

I have the table:

---------------------------------------
id (integer) | name (character varying)
---------------------------------------

I want to insert multiple rows represented by array of character varying. I have the function code:

create or replace function add_task_state( TEXT ) returns void as $$  
declare
    _str_states character varying[];
begin       
    _str_states = string_to_array($1,',');
    insert into task_states (name) values ???;  
end;
$$
language plpgsql;

How I can do this?

1
  • I can use this declaration: create or replace function add_task_state( _states character varying[] ) returns void as $$ Commented Dec 24, 2015 at 8:42

2 Answers 2

1

I assume that id is auto assigned?

Try this approach:

create or replace function add_task_state( TEXT ) returns void as $$  
begin       
    insert into task_states (name)  (select unnest(string_to_array($1, ','))); 
end;
$$
language plpgsql;

then:

select add_task_state( 'h,c,f' ) 

will give:

    id name
   ---------
    1   h
    2   c
    3   f

It's very similar to my answer here

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

1 Comment

side note : No need to use plpgsql in this case. this is enough
1

You can use FOREACH and the function should be

CREATE OR REPLACE FUNCTION add_task_state(TEXT) RETURNS void AS $$
DECLARE
   a text[] := string_to_array($1,',');
   i text;
BEGIN
FOREACH i IN ARRAY a --loop through each element in array `a`
LOOP
  insert into task_states (name) values (i);
END LOOP;
end;
$$ LANGUAGE PLPGSQL;

If your Postgres version is older than 9.1 then you can use

FOR i in 1..array_length(a, 1) LOOP
INSERT INTO task_states (name)
VALUES (a[i]);

END LOOP;

use : select add_task_state('value1,value2,value3')

Comments

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.