Search code examples
postgresqlplpgsql

How to initialize a rowtype array in pl/pgsql?


I need to declare an array of records that will be inserted into some table then. But i cannot find a way to initialize this array. Like, for table like this:

create table mytable
(
  id serial,
  value varchar
);

I need something like:

do
$$
    declare 
        rowsForTable mytable%rowtype[] := array [
           ( id=1, value='val 1' ),
           ( id=2, value='val 2' ),
           ( id=3 )
    ];

How could I achieve it? Thank you!


Solution

  • Use just mytable[] for rowsForTable datatype, not mytable%rowtype[]. Use positional row literals w/o names to initialize the array.

    -- setup
    create table mytable
    (
      id serial,
      value text
    );
    
    -- demo
    do 
    $$
    declare 
     rowsForTable mytable[] := array[(1, 'val 1'), (2, 'val 2'), (3, null)];
    begin
      insert into mytable select * from unnest (rowsForTable);
    end;
    $$;
    

    Please note the null in the third array element.