pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Gianni Ceccarelli <dakkar@thenautilus.net>
To: pgsql-general@lists.postgresql.org
Subject: Re: pass non-formated query to PL function
Date: Fri, 2 Apr 2021 10:53:57 +0100
Message-ID: <20210402105357.268bb621@nautilus> (raw)
In-Reply-To: <CALyyT7QKVUVp-Z6k_g3MR9WVSssJQdKmvPGuEVPqg=F51b8RYw@mail.gmail.com>
References: <CALyyT7QKVUVp-Z6k_g3MR9WVSssJQdKmvPGuEVPqg=F51b8RYw@mail.gmail.com>

On 2021-04-02 Joao Miguel Ferreira <joao.miguel.c.ferreira@gmail.com>
wrote:
> Is it possible, in PL/pgSQL, to pass an argument to a function which
> is actually a "query skeleton" that the method will "fill in the
> blanks" and execute it or return it to the caller after ?

you probably want to use the ``EXECUTE`` command:
https://www.postgresql.org/docs/13/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

Something like this, maybe::

  CREATE FUNCTION run_me_this(in the_query text) RETURNS record
  AS $$
  DECLARE
    this record;
  BEGIN
    EXECUTE the_query INTO this USING 1, 'foo';
    RETURN this;
  END;
  $$ LANGUAGE plpgsql;

  CREATE TABLE test(id serial primary key,name text,value text);
  INSERT INTO test(name,value) VALUES ('foo','something');

  SELECT *
  FROM run_me_this('select value from test where id=$1 and name=$2')
       x(value text);

Notice, though, that ``EXECUTE ... INTO`` will only assign *the first
row* of the results to the given variable (``this`` in my
example). I'm not sure how to work around this limitation.

-- 
	Dakkar - <Mobilis in mobile>
	GPG public key fingerprint = A071 E618 DD2C 5901 9574
	                             6FE2 40EA 9883 7519 3F88
	                    key id = 0x75193F88






view thread (4+ messages)  latest in thread

Message-ID: <20210402105357.268bb621@nautilus>
Permalink:  ../20210402105357.268bb621@nautilus/
Also on:    postgresql.org/message-id/20210402105357.268bb621@nautilus

 · 

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 from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: dakkar@thenautilus.net
  Subject: Re: pass non-formated query to PL function
  In-Reply-To: <20210402105357.268bb621@nautilus>
  References: <CALyyT7QKVUVp-Z6k_g3MR9WVSssJQdKmvPGuEVPqg=F51b8RYw@mail.gmail.com> <20210402105357.268bb621@nautilus>

* 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