Re: Appending to an array - Mailing list pgsql-general

From Joe Conway
Subject Re: Appending to an array
Date
Msg-id 3E9C39FA.8050601@joeconway.com
Whole thread Raw
In response to Appending to an array  ("Jay O'Connor" <joconnor@cybermesa.com>)
List pgsql-general
Jay O'Connor wrote:
>     I've got a tablewhere one of the columns contains an array.  What I'm
> trying to do is to append or insert into the array.  I know I can so
> something like..
>     UPDATE mytable set myarray[10] = 'some value' WHERE...
>
> ..to change a particular array element, and this be used to extend the
> array if the array is not that size yet, but what I need to figure out is
> how to do that when I don't know the size of the array at any given time.
>

How's this? (requires version 7.3.x)

CREATE OR REPLACE FUNCTION array_next(text[]) returns int AS '
DECLARE
   arr alias for $1;
   high int;
BEGIN
   high := 1 +
     replace(split_part(array_dims(arr),'':'',2),'']'','''')::int;
   RETURN high;
END;
' LANGUAGE 'plpgsql' IMMUTABLE STRICT;

create table mytable (myarray text[]);
insert into mytable values ('{"abc","d e f"}');
update mytable set myarray[array_next(myarray)] = 'new element';
regression=# select * from mytable;
            myarray
-----------------------------
  {abc,"d e f","new element"}
(1 row)

HTH,

Joe


pgsql-general by date:

Previous
From: "scott.marlowe"
Date:
Subject: Re: How to change data type in column ?
Next
From: Guy Fraser
Date:
Subject: Re: Arrays ... need clarification....