Re: How to pass array of values to a stored procedure

From: "Tony Wasson" <ajwasson(at)gmail(dot)com>
To: "Curtis Scheer" <Curtis(at)daycos(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: How to pass array of values to a stored procedure
Date: 2006-07-18 17:24:36
Message-ID: 6d8daee30607181024w74cf4673gf2f55066219dc21@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On 7/18/06, Curtis Scheer <Curtis(at)daycos(dot)com> wrote:
> Does anyone have any examples of how I would make a stored procedure in
> plpgsql that would allow for passing a list or arrays of values to be used
> in an sql IN clause? Like so: select * from table where field1 in (values).
>

Here's a very simple example. However, I think passing arrays of INTs
around is dirty. I wasn't able to do this without a FOR ...IN EXECUTE
statement.

CREATE TABLE ids
(
id INTEGER
, PRIMARY KEY (id)
);

INSERT INTO ids VALUES (1);
INSERT INTO ids VALUES (2);
INSERT INTO ids VALUES (3);

CREATE OR REPLACE FUNCTION example_array_input(INT[]) RETURNS SETOF ids AS
$BODY$
DECLARE
in_clause ALIAS FOR $1;
clause TEXT;
rec RECORD;
BEGIN
-- conver the array to a text string and make it LOOK like an
IN statement
clause := in_clause;
clause := trim(leading '{' FROM clause);
clause := trim(trailing '}' FROM clause);

FOR rec IN EXECUTE 'SELECT id FROM ids WHERE id IN (' || clause || ');'
LOOP
RETURN NEXT rec;
END LOOP;
-- final return
RETURN;
END
$BODY$ language plpgsql;

SELECT * FROM example_array_input('{1,2,4,5,6}'::INT[]);

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tony Wasson 2006-07-18 17:33:58 Re: How to pass array of values to a stored procedure
Previous Message Tom Lane 2006-07-18 17:15:28 Re: How to pass array of values to a stored procedure