Re: Converting value to array

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Sean Davis" <sdavis2(at)mail(dot)nih(dot)gov>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Converting value to array
Date: 2005-02-05 17:10:36
Message-ID: 23710.1107623436@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

"Sean Davis" <sdavis2(at)mail(dot)nih(dot)gov> writes:
> I have a column in my table block_sizes(varchar) that looks like:

> 12,23,
> 234,23,
> 78,64,28,

> i.e., comma-separated integer values (and the included trailing comma). =
> I would like to convert these each to an array and store in another =
> column.

> '{' || rtrim(block_sizes,',') || '}'

That is one correct way to compute the external textual representation
of the array you want. The trick is to get it fed to the array datatype
input converter. The main SQL parser is pretty strongly typed and I'm
not sure there is any way to get it to make that conversion. However
several of the PLs are pretty lax about cross-type conversions; in
particular you could do this in plpgsql. Untested, but

create function block_sizes_to_array(varchar) returns int[] as '
declare x int[];
begin
x := ''{'' || rtrim($1, '','') || ''}'';
return x;
end' language plpgsql;

should work well enough. plpgsql will observe that the text result it
got from the expression is not the right type to assign to the int[]
variable x, and will deal with this by converting to external textual
form (a no-op for the text side) and back again.

regards, tom lane

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Les Carter 2005-02-06 02:21:04 table name as function argument?
Previous Message Michael Fuhr 2005-02-05 16:41:47 Re: Converting value to array