Re: PL/pgSQL multidimension (matrix) array in function

From: Joe Conway <mail(at)joeconway(dot)com>
To: sergio(dot)fantinel(at)lnl(dot)infn(dot)it
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: PL/pgSQL multidimension (matrix) array in function
Date: 2004-09-21 04:44:02
Message-ID: 414FB192.5060100@joeconway.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Sergio Fantinel wrote:
> I found how to use, inside a PL/pgSQL function, a two-dimensions array
> (matrix).
> There is a limitation: the number of the 'columns' of the matrix is
> fixed at declaration time (in DECLARE section) and you need to manually
> initialize all the elements in the first 'row' of the matrix.

You should use '{}' to initialize the array to empty. See below for an
example:

CREATE OR REPLACE FUNCTION testarray (integer, integer) RETURNS SETOF
integer[] AS'
DECLARE
n alias for $1; -- number of rows is passed as argument
i INTEGER;
j integer;
k alias for $2; -- matrix columns number
a integer[];
begin
for i in 1..n loop
a := ''{}''; -- create empty array
for j in 1..k loop
a := a || i;
return next a;
end loop;
end loop;
return;
end;
'LANGUAGE 'plpgsql';

regression=# select * from testarray(2,3);
testarray
-----------
{1}
{1,1}
{1,1,1}
{2}
{2,2}
{2,2,2}
(6 rows)

HTH,

Joe

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2004-09-21 05:19:33 Re: JOIN performance
Previous Message Dean Gibson (DB Administrator) 2004-09-21 04:41:40 Re: JOIN performance