Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lSGVT-0006OJ-Bt for pgsql-general@arkaria.postgresql.org; Fri, 02 Apr 2021 09:54:23 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1lSGVS-0008CE-6J for pgsql-general@arkaria.postgresql.org; Fri, 02 Apr 2021 09:54:22 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lSGVR-0008C7-VU for pgsql-general@lists.postgresql.org; Fri, 02 Apr 2021 09:54:21 +0000 Received: from mail.thenautilus.net ([5.79.87.27]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lSGVL-0003GF-Bv for pgsql-general@lists.postgresql.org; Fri, 02 Apr 2021 09:54:20 +0000 Received: (qmail 26374 invoked from network); 2 Apr 2021 09:53:58 -0000 Received: from unknown (HELO nautilus) (dakkar@::ffff:81.2.107.215) by 0 with ESMTPA; 2 Apr 2021 09:53:58 -0000 Date: Fri, 2 Apr 2021 10:53:57 +0100 From: Gianni Ceccarelli To: pgsql-general@lists.postgresql.org Subject: Re: pass non-formated query to PL function Message-ID: <20210402105357.268bb621@nautilus> In-Reply-To: References: X-Mailer: Claws Mail 3.99.0git34 (GTK+ 3.24.24; x86_64-pc-linux-gnu) MIME-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk On 2021-04-02 Joao Miguel Ferreira 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 - GPG public key fingerprint = A071 E618 DD2C 5901 9574 6FE2 40EA 9883 7519 3F88 key id = 0x75193F88