Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1j0FZ8-0004Y9-A0 for pgsql-admin@arkaria.postgresql.org; Sat, 08 Feb 2020 02:09:50 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1j0FZ7-00017M-5G for pgsql-admin@arkaria.postgresql.org; Sat, 08 Feb 2020 02:09:49 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1j0FZ6-00017F-RR for pgsql-admin@lists.postgresql.org; Sat, 08 Feb 2020 02:09:48 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1j0FZ4-0005IS-LQ for pgsql-admin@postgresql.org; Sat, 08 Feb 2020 02:09:48 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id 01829icX029970; Fri, 7 Feb 2020 21:09:44 -0500 From: Tom Lane To: Wells Oliver cc: pgsql-admin Subject: Re: plpgsql, dynamic variable lengths.. In-reply-to: References: Comments: In-reply-to Wells Oliver message dated "Fri, 07 Feb 2020 16:38:12 -0800" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <29968.1581127784.1@sss.pgh.pa.us> Date: Fri, 07 Feb 2020 21:09:44 -0500 Message-ID: <29969.1581127784@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Wells Oliver writes: > I am trying to create a plpgsql function which accepts a jsonb object as > its parameter. > This jsonb can have up to three keys, and I am trying to build out the > dynamic SQL like this. I want to be able to pass a variable number of > params to the RETURN QUERY EXECUTE ... USING ... because it can be 0 params > in the JSONB object, or one, or two. > What's the missing piece here? How can I adjust my USING to accomplish this? I think your USING is probably fine. But you made all the SQL fragments refer to $1: > begin > SQLSTRING := 'SELECT * FROM mytable WHERE true'; > if args->>'col1' is not null then > SQLSTRING := SQLSTRING || ' AND col1 = $1'; > end if; > if args->>'col2' is not null then > SQLSTRING := SQLSTRING || ' AND col2 = $1'; > end if; > if args->>'col3' is not null then > SQLSTRING := SQLSTRING || ' AND col3 = $1'; > end if; Of course those need to be $1, $2, $3. regards, tom lane