pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tony Wasson <ajwasson@gmail.com>
To: Curtis Scheer <Curtis@daycos.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: How to pass array of values to a stored procedure
Date: Tue, 18 Jul 2006 10:24:36 -0700
Message-ID: <6d8daee30607181024w74cf4673gf2f55066219dc21@mail.gmail.com> (raw)
In-Reply-To: <031936836C46D611BB1B00508BE7345D048DAAB8@gatekeeper.daycos.com>
References: <031936836C46D611BB1B00508BE7345D048DAAB8@gatekeeper.daycos.com>

On 7/18/06, Curtis Scheer <Curtis@daycos.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[]);



view thread (5+ messages)  latest in thread

Message-ID: <6d8daee30607181024w74cf4673gf2f55066219dc21@mail.gmail.com>
Permalink:  ../6d8daee30607181024w74cf4673gf2f55066219dc21@mail.gmail.com/
Also on:    postgresql.org/message-id/6d8daee30607181024w74cf4673gf2f55066219dc21@mail.gmail.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: ajwasson@gmail.com, Curtis@daycos.com
  Subject: Re: How to pass array of values to a stored procedure
  In-Reply-To: <6d8daee30607181024w74cf4673gf2f55066219dc21@mail.gmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox